How to apply the background color for the ImageSpan in Android?

為{幸葍}努か 提交于 2020-03-02 12:22:28

问题


I want to apply the background color for the Image span dynamically in Android.

Could you please suggest any ideas?


回答1:


You can't use BackgroundColorSpan and ImageSpan at the same time. The idea is creating an ImageSpan from LayerDrawable with background and image layers. Please look at the following code:

Kotlin:

val span: Spannable = SpannableString("This is   ic launcher with background")
val myImage: Drawable = resources.getDrawable(R.drawable.ic_launcher_foreground)
val background = ShapeDrawable()
background.paint.color = Color.RED
val layerDrawable = LayerDrawable(arrayOf(background, myImage))
layerDrawable.setBounds(0, 0, 64, 64)
val image = ImageSpan(layerDrawable, ImageSpan.ALIGN_BASELINE)
span.setSpan(image, 8, 9, Spannable.SPAN_INCLUSIVE_EXCLUSIVE)

textView.setText(span)


Java:

Spannable span = new SpannableString("This is   ic launcher with background");
Drawable myImage = context.getResources().getDrawable(R.drawable.ic_launcher_foreground);
ShapeDrawable background = new ShapeDrawable();
background.getPaint().setColor(Color.RED);
LayerDrawable layerDrawable = new LayerDrawable(new Drawable[]{background, myImage});
layerDrawable.setBounds(0, 0, 64, 64);
ImageSpan image = new ImageSpan(layerDrawable, ImageSpan.ALIGN_BASELINE);
span.setSpan(image, 8, 9, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);

textView.setText(span);


The result will be like this:




回答2:


  1. You can try to use BackgroundColorSpan with ImageSpan for the same position
  2. You can create an image with the color you need


来源:https://stackoverflow.com/questions/60057201/how-to-apply-the-background-color-for-the-imagespan-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!