矢量可在文本视图内的任何位置绘制(不在其外部)

Vector drawable in any location within text view (not outside of it)

有没有办法以编程方式在文本视图中的任何位置添加可绘制对象,而不必将其放置在文本视图的特定一侧?以下代码在使用 unicode 字符时有效,但我想尝试使用矢量可绘制对象。

textView.text = getString(R.string.app_settings) + " \u2794 " + getString(R.string.display)

对我来说,ImageSpan 很管用。 您可以放置​​一个分隔符并将其替换为可绘制对象。我在这个例子中使用了 google 图标

:

带分隔符替换的代码:

    Drawable drawable = ContextCompat.getDrawable(this, R.drawable.google_icon);
    drawable.setBounds(0, 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);

或者,您可以将可绘制对象放在任何索引上,例如:

span.setSpan(image, start_index, end_index, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);

PS:文字外观我用的是Display1。您需要根据自己的需要更改drawable bounds。