Skip to content

Instantly share code, notes, and snippets.

@logcat
Last active April 10, 2017 19:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save logcat/64234419a935f1effc67 to your computer and use it in GitHub Desktop.
Save logcat/64234419a935f1effc67 to your computer and use it in GitHub Desktop.
Android textview which loads resource drawable and display it as part of text view in defined place. Use android.text.Html.
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.text.Html;
import android.text.Html.ImageGetter;
import android.text.Spanned;
import android.util.AttributeSet;
import android.widget.TextView;
/**
* XXX does not support android:drawable, only current app packaged icons
*
* Use it with strings like <string name="text"><![CDATA[Some text <img src="some_image"></img> with image in between]]></string>
* assuming there is @drawable/some_image in project files
*
* Must be accompanied by styleable
* <declare-styleable name="HtmlTextView">
* <attr name="android:text" />
* </declare-styleable>
*/
public class HtmlTextView extends TextView {
public HtmlTextView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.HtmlTextView);
String html = context.getResources().getString(typedArray.getResourceId(R.styleable.HtmlTextView_android_text, 0));
typedArray.recycle();
Spanned spannedFromHtml = Html.fromHtml(html, new DrawableImageGetter(), null);
setText(spannedFromHtml);
}
private class DrawableImageGetter implements ImageGetter {
@Override
public Drawable getDrawable(String source) {
Resources res = getResources();
int drawableId = res.getIdentifier(source, "drawable", getContext().getPackageName());
Drawable drawable = res.getDrawable(drawableId, getContext().getTheme());
int size = (int) getTextSize();
int width = size;
int height = size;
// int width = drawable.getIntrinsicWidth();
// int height = drawable.getIntrinsicHeight();
drawable.setBounds(0, 0, width, height);
return drawable;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment