问题描述
是否可以通过编程方式在文本视图内的任何位置添加可绘制对象,而不必将其放置在文本视图的特定侧面上?下面的代码在使用Unicode字符时有效,但我想在矢量可绘制对象上尝试相同的代码。
textView.text = getString(R.string.app_settings) + " \u2794 " + getString(R.string.display)
解决方法
对于我来说,ImageSpan可以工作。 您可以放置定界符并将其替换为drawable。在此示例中,我使用了Google图标
带有定界符替换的代码:
Drawable drawable = ContextCompat.getDrawable(this,R.drawable.google_icon);
drawable.setBounds(0,100,100);
String text = " Google %google_icon% icon";
String delimiter = "%google_icon%";
int icon_index = text.indexOf("%google_icon%");
text = text.replace(delimiter," ");
Spannable span = new SpannableString(text);
ImageSpan image = new ImageSpan(drawable,ImageSpan.ALIGN_BASELINE);
span.setSpan(image,icon_index,icon_index+1,Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
textView.setText(span);
或者,您可以将drawable放置在任何索引上,例如:
span.setSpan(image,start_index,end_index,Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
PS:我在文本外观中使用了Display1。您需要根据自己的需要更改可绘制范围。