简体   繁体   English

Android - 具有不同背景颜色的TextView

[英]Android - TextView with different background colors

Is it possible to have a TextView with different background colors. 是否可以使用具有不同背景颜色的TextView。 Eg. 例如。 If the text is "This is a test", is it possible to set different background color for the four words? 如果文本是“这是一个测试”,是否可以为这四个单词设置不同的背景颜色?

Yes. 是。

SpannableString spannableString = new SpannableString(getString(R.string.hello_world));
Object greenSpan = new BackgroundColorSpan(Color.GREEN);
Object redSpan = new BackgroundColorSpan(Color.RED);
spannableString.setSpan(greenSpan, 0, 6, 0);
spannableString.setSpan(redSpan, 6, spannableString.length(), 0);

TextView textView = (TextView) findViewById(R.id.text);
textView.setText(spannableString);

Produces: 生产:

在此输入图像描述

EDIT: There are a lot of different spannable types, you can do much nicer looking things than my basic example. 编辑:有很多不同的spannable类型,你可以做比我的基本示例更好看的东西。 Check out this article. 看看这篇文章。

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

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