How To Apply The Background Color For The Imagespan In Android?
I want to apply the background color for the Image span dynamically in Android. Could you please suggest any ideas?
Solution 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:
Spannablespan=newSpannableString("This is ic launcher with background");
DrawablemyImage= context.getResources().getDrawable(R.drawable.ic_launcher_foreground);
ShapeDrawablebackground=newShapeDrawable();
background.getPaint().setColor(Color.RED);
LayerDrawablelayerDrawable=newLayerDrawable(newDrawable[]{background, myImage});
layerDrawable.setBounds(0, 0, 64, 64);
ImageSpanimage=newImageSpan(layerDrawable, ImageSpan.ALIGN_BASELINE);
span.setSpan(image, 8, 9, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
textView.setText(span);
The result will be like this:
Solution 2:
- You can try to use
BackgroundColorSpan
withImageSpan
for the same position - You can create an image with the color you need
Solution 3:
The accepted answer gets the job done. Additionally, if you want to create LayerDrawable
from XML, here is an example.
[src/main/res/drawable/layer_drawable.xml]
<?xml version="1.0" encoding="utf-8"?><layer-listxmlns:android="http://schemas.android.com/apk/res/android"><item><shapeandroid:shape="rectangle"><solidandroid:color="@color/your_color" /></shape></item><itemandroid:drawable="@drawable/ic_your_image" /></layer-list>
[In your Fragment]
ResourcesCompat.getDrawable(resources, R.drawable.layer_drawable, null)?.let { layerDrawable ->
val size = resources.getDimension(R.dimen.layer_drawable_size).toInt()
layerDrawable.setBounds(0, 0, size, size) // Not sure how to do this in XML.
val imageSpan = ImageSpan(layerDrawable)
...
}
Post a Comment for "How To Apply The Background Color For The Imagespan In Android?"