简体   繁体   English

如何在 Android 中为 ImageSpan 应用背景颜色?

[英]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.我想在 Android 中动态应用图像跨度的背景颜色。

Could you please suggest any ideas?你能提出任何想法吗?

You can't use BackgroundColorSpan and ImageSpan at the same time.您不能同时使用BackgroundColorSpanImageSpan The idea is creating an ImageSpan from LayerDrawable with background and image layers.这个想法是从带有背景和图像层的LayerDrawable创建一个 ImageSpan。 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:结果将是这样的:

在此处输入图片说明

  1. You can try to use BackgroundColorSpan with ImageSpan for the same position您可以尝试将BackgroundColorSpanImageSpan用于相同的位置
  2. You can create an image with the color you need您可以使用您需要的颜色创建图像

The accepted answer gets the job done.接受的答案可以完成工作。 Additionally, if you want to create LayerDrawable from XML, here is an example.此外,如果您想从 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)
    ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM