TextView设置某些字颜色
时间: 2023-09-12 20:12:14 浏览: 46
您可以使用SpannableString类和ForegroundColorSpan类来设置TextView中某些字的颜色。以下是一个示例:
```java
String text = "Hello World";
SpannableString spannableString = new SpannableString(text);
ForegroundColorSpan colorSpan = new ForegroundColorSpan(Color.RED);
spannableString.setSpan(colorSpan, 0, 5, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(spannableString);
```
这将把“Hello”这个单词的颜色设置为红色。您可以根据需要更改起始和结束索引来设置不同的文本范围和颜色。
相关问题
android textview设置字体颜色
你可以使用 TextView 的 setTextColor() 方法来设置字体颜色,例如:
textView.setTextColor(Color.RED);
其中 Color.RED 是一个预定义的颜色常量,你也可以使用其他颜色常量或自定义颜色。
textview 如何设置多颜色文字
要在安卓 TextView 中设置多颜色的文字,可以使用 SpannableString 和 SpannableStringBuilder 类来实现。下面是一个例子:
```java
TextView textView = findViewById(R.id.textView);
SpannableStringBuilder builder = new SpannableStringBuilder();
String redText = "红色文字";
SpannableString redSpannable= new SpannableString(redText);
redSpannable.setSpan(new ForegroundColorSpan(Color.RED), 0, redText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
builder.append(redSpannable);
String blueText = "蓝色文字";
SpannableString blueSpannable = new SpannableString(blueText);
blueSpannable.setSpan(new ForegroundColorSpan(Color.BLUE), 0, blueText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
builder.append(blueSpannable);
// 添加更多颜色的文字...
textView.setText(builder);
```
在这个例子中,我们创建了一个 SpannableStringBuilder 对象,用于构建具有多种颜色的文字。我们创建了两个不同颜色的 SpannableString,分别设置了它们的前景色 (ForegroundColorSpan)。然后将它们添加到 SpannableStringBuilder 中,并最终将其设置为 TextView 的文本。
你可以根据需要添加更多颜色的文字,只需创建新的 SpannableString,并设置其前景色即可。