如何在 Android 中为 ImageSpan 应用背景颜色? [英] How to apply the background color for the ImageSpan in Android?

查看:79
本文介绍了如何在 Android 中为 ImageSpan 应用背景颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 Android 中动态应用图像跨度的背景颜色.

你能提出任何建议吗?

解决方案

BackgroundColorSpanImageSpan 不能同时使用.这个想法是从带有背景和图像层的

I want to apply the background color for the Image span dynamically in Android.

Could you please suggest any ideas?

解决方案

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:

这篇关于如何在 Android 中为 ImageSpan 应用背景颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆