我想在Android中动态为图像span应用背景颜色。
请给出任何建议?
BackgroundColorSpan
和ImageSpan
。想法是从带有背景和图片层的LayerDrawable创建ImageSpan,请查看以下代码: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);
被接受的答案完成了工作。此外,如果您想从XML创建LayerDrawable
,这里有一个例子。
[src/main/res/drawable/layer_drawable.xml]
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="@color/your_color" />
</shape>
</item>
<item android: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)
...
}
BackgroundColorSpan
和 ImageSpan