这个答案是基于这个优秀的答案被18446744073709551615。他们的解决方案虽然很有帮助,但并不能将图像图标的大小与周围的文本对齐。它还没有将图标颜色设置为周围文本的颜色。
下面的解决方案带有一个白色方形图标,使其适合周围文本的大小和颜色。
public class TextViewWithImages extends TextView {
private static final String DRAWABLE = "drawable";
public static final String PATTERN = "\\Q[img src=\\E([a-zA-Z0-9_]+?)\\Q/]\\E";
public TextViewWithImages(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public TextViewWithImages(Context context, AttributeSet attrs) {
super(context, attrs);
}
public TextViewWithImages(Context context) {
super(context);
}
@Override
public void setText(CharSequence text, BufferType type) {
final Spannable spannable = getTextWithImages(getContext(), text, getLineHeight(), getCurrentTextColor());
super.setText(spannable, BufferType.SPANNABLE);
}
private static Spannable getTextWithImages(Context context, CharSequence text, int lineHeight, int colour) {
final Spannable spannable = Spannable.Factory.getInstance().newSpannable(text);
addImages(context, spannable, lineHeight, colour);
return spannable;
}
private static boolean addImages(Context context, Spannable spannable, int lineHeight, int colour) {
final Pattern refImg = Pattern.compile(PATTERN);
boolean hasChanges = false;
final Matcher matcher = refImg.matcher(spannable);
while (matcher.find()) {
boolean set = true;
for (ImageSpan span : spannable.getSpans(matcher.start(), matcher.end(), ImageSpan.class)) {
if (spannable.getSpanStart(span) >= matcher.start()
&& spannable.getSpanEnd(span) <= matcher.end()) {
spannable.removeSpan(span);
} else {
set = false;
break;
}
}
final String resName = spannable.subSequence(matcher.start(1), matcher.end(1)).toString().trim();
final int id = context.getResources().getIdentifier(resName, DRAWABLE, context.getPackageName());
if (set) {
hasChanges = true;
spannable.setSpan(makeImageSpan(context, id, lineHeight, colour),
matcher.start(),
matcher.end(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
);
}
}
return hasChanges;
}
private static ImageSpan makeImageSpan(Context context, int drawableResId, int size, int colour) {
final Drawable drawable = context.getResources().getDrawable(drawableResId);
drawable.mutate();
drawable.setColorFilter(colour, PorterDuff.Mode.MULTIPLY);
drawable.setBounds(0, 0, size, size);
return new ImageSpan(drawable, ImageSpan.ALIGN_BOTTOM);
}
}
如何使用:
只需在文本中嵌入对所需图标的引用即可。文本是通过编程方式textView.setText(R.string.string_resource);
设置还是在xml中设置都没有关系。
要嵌入名为example.png的可绘制图标,请在文本中包含以下字符串:[img src=example/]
。
例如,字符串资源可能如下所示:
<string name="string_resource">This [img src=example/] is an icon.</string>