英文:
Kotlin -How to Change Text Color of a SpannableString with an Image
问题
Sure, here is the translated content:
我有一个带有图像的字符串。我能够将图像颜色更改为绿色,但无法将文本颜色更改为绿色。它保持为黑色。
"abc is available" 也应该是绿色的。
val span = SpannableStringBuilder()
span.append("abc is available")
span.setSpan(R.color.myGreenColor, 0, span.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
span.append(" ")
val unwrappedDrawable = AppCompatResources.getDrawable(this, R.drawable.checkmark_icon)?.mutate()
if (unwrappedDrawable != null) {
val wrappedDrawable = DrawableCompat.wrap(unwrappedDrawable)
DrawableCompat.setTint(wrappedDrawable, ContextCompat.getColor(this, R.color.myGreenColor))
val lineHeight = binding.myTextView.lineHeight
wrappedDrawable.setBounds(0, 0, lineHeight, lineHeight)
val image = ImageSpan(wrappedDrawable, 0)
span.setSpan(image, span.length -1, span.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
binding.myTextView.text = span
}
I hope this helps!
英文:
I have a string with an image on the back. I'm able to change the image color to green but I can't get the text color to change to green also. It stays black.
"abc is available" should be green too
val span = SpannableStringBuilder()
span.append("abc is available")
span.setSpan(R.color.myGreenColor, 0, span.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
span.append(" ")
val unwrappedDrawable = AppCompatResources.getDrawable(this, R.drawable.checkmark_icon)?.mutate()
if (unwrappedDrawable != null) {
val wrappedDrawable = DrawableCompat.wrap(unwrappedDrawable)
DrawableCompat.setTint(wrappedDrawable, ContextCompat.getColor(this, R.color.myGreenColor))
val lineHeight = binding.myTextView.lineHeight
wrappedDrawable.setBounds(0, 0, lineHeight, lineHeight)
val image = ImageSpan(wrappedDrawable, 0)
span.setSpan(image, span.length -1, span.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
binding.myTextView.text = span
}
答案1
得分: 2
setSpan()
方法的第一个参数不应该传递颜色资源,因为它将其视为Object
类型;但这不会产生任何影响。
setSpan()
应该接受实现了ParcelableSpan
的对象。
> span.setSpan(R.color.myGreenColor, 0, span.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
因此,这行代码不会产生任何影响;而是应该用ForegroundColorSpan
替换它:
span.setSpan(ForegroundColorSpan(ResourcesCompat.getColor(resources, R.color.myGreenColor, null)),
0, span.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
英文:
The setSpan()
method shouldn't take a color resource at the first parameter, it accepts it as it's of type Object
; but it won't have any affection.
setSpan()
should take an object that implements ParcelableSpan
.
> span.setSpan(R.color.myGreenColor, 0, span.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
So, this line of code won't have any affect; instead you'd replace it with ForegroundColorSpan
:
span.setSpan(ForegroundColorSpan(ResourcesCompat.getColor(resources, R.color.myGreenColor, null)),
0, span.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论