不久前有一个similiar question,有人想出了一个很棒的解决方案。我刚刚稍微调整了一下,这样图像大小总是和线条一样高。所以基本上你的图标会随 textSize 缩放。
第 1 步 - 创建新视图
创建一个扩展 TextView 的新 Java 类
public class TextViewWithImages extends TextView {
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) {
Spannable s = getTextWithImages(getContext(), text, this.getLineHeight());
super.setText(s, BufferType.SPANNABLE);
}
private static final Spannable.Factory spannableFactory = Spannable.Factory.getInstance();
private static boolean addImages(Context context, Spannable spannable, float height) {
Pattern refImg = Pattern.compile("\\Q[img src=\\E([a-zA-Z0-9_]+?)\\Q/]\\E");
boolean hasChanges = false;
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;
}
}
String resName = spannable.subSequence(matcher.start(1), matcher.end(1)).toString().trim();
int id = context.getResources().getIdentifier(resName, "drawable", context.getPackageName());
Drawable mDrawable = context.getResources().getDrawable(id);
mDrawable.setBounds(0, 0, (int)height, (int)height);
if (set) {
hasChanges = true;
spannable.setSpan( new ImageSpan(mDrawable),
matcher.start(),
matcher.end(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
);
}
}
return hasChanges;
}
private static Spannable getTextWithImages(Context context, CharSequence text, float height) {
Spannable spannable = spannableFactory.newSpannable(text);
addImages(context, spannable, height);
return spannable;
}
}
第 2 步 - 布局中的用法
现在在你的 layout-xml 中使用 TextViewWithImages 类
<com.stacko.examples.TextViewWithImages
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="14sp"
android:text="@string/my_string_with_icons" />
第 3 步 - 创建带有图标的字符串
正如您在TextViewWithImages 类的addImages(...) 函数中所见,字符串中的特殊模式([img src=my_icon/])用于添加图像。
所以这里有一个例子:
<string name="my_string_with_icons">The [img src=ic_action_trash/] is used to delete an item while the [img src=ic_action_edit/] is to edit one.</string>
输出:
如前所述,它将随您的 textSize 扩展:
正如最初所说,这篇文章的大部分内容来自18446744073709551615 答案here。我认为这应该作为一个库发布,因为在文本中包含图像是一个常见的用例。 :