首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在安卓系统中为ImageSpan应用背景色?

如何在安卓系统中为ImageSpan应用背景色?
EN

Stack Overflow用户
提问于 2020-02-04 20:14:07
回答 3查看 709关注 0票数 3

我想在Android中动态应用Image span的背景色。

你能给我一些建议吗?

EN

回答 3

Stack Overflow用户

发布于 2020-02-10 20:19:24

您不能同时使用BackgroundColorSpanImageSpan。这个想法是从LayerDrawable创建一个具有背景和图像层的ImageSpan。请看下面的代码:

Kotlin:

代码语言:javascript
运行
复制
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:

代码语言:javascript
运行
复制
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);

结果将如下所示:

票数 3
EN

Stack Overflow用户

发布于 2020-02-04 20:27:22

  1. 您可以尝试将BackgroundColorSpanImageSpan用于相同的位置
  2. 您可以创建具有所需颜色的图像
票数 0
EN

Stack Overflow用户

发布于 2021-08-06 05:43:59

被接受的答案可以完成工作。此外,如果您想从XML创建LayerDrawable,这里有一个示例。

代码语言:javascript
运行
复制
[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>
代码语言:javascript
运行
复制
[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)
    ...
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60057201

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档