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

2023-09-07 09:50:50 作者:背叛的冲刷。

是否有可能有不同的背景颜色一个TextView。例如。如果文本是这是一个测试,它是可以设置不同的背景色为四个字?

Is it possible to have a TextView with different background colors. Eg. If the text is "This is a test", is it possible to set different background color for the four words?

推荐答案

是的。

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);

产地:

编辑:有很多不同的spannable类型,您可以做的更好看的东西比我的基本的例子。请查看这的文章。

There are a lot of different spannable types, you can do much nicer looking things than my basic example. Check out this article.