Android:使用 TextView.setText() 为字符串的一部分着色?

标签 android textview

我希望通过 .setText("") 方法更改 TextView View 的文本,同时为文本的一部分着色(或使其变为粗体、斜体、透明等)而不是其余部分。例如:

title.setText("Your big island <b>ADVENTURE!</b>";

我知道上面的代码不正确,但它有助于说明我想要实现的目标。我该怎么做?

最佳答案

使用 spans .

例子:

final SpannableStringBuilder sb = new SpannableStringBuilder("your text here");

// Span to set text color to some RGB value
final ForegroundColorSpan fcs = new ForegroundColorSpan(Color.rgb(158, 158, 158)); 

// Span to make text bold
final StyleSpan bss = new StyleSpan(android.graphics.Typeface.BOLD); 

// Set the text color for first 4 characters
sb.setSpan(fcs, 0, 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE); 

// make them also bold
sb.setSpan(bss, 0, 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE); 

yourTextView.setText(sb);

关于Android:使用 TextView.setText() 为字符串的一部分着色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4897349/

相关文章:

android - SharedPreferences 保存数据多长时间?

android - FrameLayout 内 View 上的奇怪 Alpha 动画问题

ios - 当 TextView 中没有文本时如何禁用按钮?

Android:单击按钮时如何显示TextView?

android - Android Recyclerview运行缓慢

android - ActionBar 共享项目产生 "Android System"thingy

java - Android RAM页面大小?

Android TextView动画,一个字一个字

android - 显示版本名称

android - 动态添加textview android的问题