Vector drawable 在文本视图内的任何位置(不是在其外部)

huangapple go评论79阅读模式
英文:

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);

Vector drawable 在文本视图内的任何位置(不是在其外部)

英文:

Is there a way to add a drawable in any position within a text view programmatically without having to position it on a particular side of a text view? The following code works when using unicode character but I want to try the same with a vector drawable.

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

Vector drawable 在文本视图内的任何位置(不是在其外部)

答案1

得分: -1

对于我来说,ImageSpan起作用。
您可以放置一个分隔符并将其替换为可绘制的对象。在此示例中,我使用了Google图标。

Vector drawable 在文本视图内的任何位置(不是在其外部):

带有分隔符替换的代码:

    Drawable drawable = ContextCompat.getDrawable(this, R.drawable.google_icon);
    drawable.setBounds(0, 0, 100,100);

    String text = " Google %google_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。您需要根据自己的需求更改可绘制对象的边界。

英文:

For me, ImageSpan works.
You can put a delimiter and replace it with the drawable. I used a google icon in this example

Vector drawable 在文本视图内的任何位置(不是在其外部):

Code with delimiter replacement:

    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);

Or, you can place the drawable on any index like:

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

PS: I used Display1 in text appearance. You need to change drawable bounds according to your own needs.

huangapple
  • 本文由 发表于 2020年8月17日 06:23:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/63442459.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定