我的意思是,是否可以在单个字符串中将文本“This text is blue”更改为蓝色?一定有办法……
<TextView
android:gravity="left"
android:padding="3dip"
android:text="This text is white. This text is blue."
android:textColor="#ffffff"
android:textSize="22dp"/>
最佳答案
是的,有可能。为此,您需要使用 SpannableString
和 ForegroundColorSpan
.
这应该看起来像这样:
SpannableStringBuilder builder = new SpannableStringBuilder();
String red = "this is red";
SpannableString redSpannable= new SpannableString(red);
redSpannable.setSpan(new ForegroundColorSpan(Color.RED), 0, red.length(), 0);
builder.append(redSpannable);
String white = "this is white";
SpannableString whiteSpannable= new SpannableString(white);
whiteSpannable.setSpan(new ForegroundColorSpan(Color.WHITE), 0, white.length(), 0);
builder.append(whiteSpannable);
String blue = "this is blue";
SpannableString blueSpannable = new SpannableString(blue);
blueSpannable.setSpan(new ForegroundColorSpan(Color.BLUE), 0, blue.length(), 0);
builder.append(blueSpannable);
mTextView.setText(builder, BufferType.SPANNABLE);
关于java - 是否可以将字符串中的文本颜色更改为 Java 中的多种颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8405661/