英文:
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);
英文:
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)
答案1
得分: -1
对于我来说,ImageSpan起作用。
您可以放置一个分隔符并将其替换为可绘制的对象。在此示例中,我使用了Google图标。
带有分隔符替换的代码:
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
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论