问题
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:
- You can try to use
BackgroundColorSpan
withImageSpan
for the same position - 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