Android:使用 TextView.setText() 为字符串的一部分着色? [英] Android: Coloring part of a string using TextView.setText()?

查看:20
本文介绍了Android:使用 TextView.setText() 为字符串的一部分着色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am looking to change the text of a TextView view via the .setText("") method while also coloring a part of the text (or making it bold, italic, transparent, etc.)and not the rest. For example:

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

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

I know the above code is incorrect but it helps illustrate what I would like to achieve. How would I do this?

推荐答案

使用跨度.

例子:

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() 为字符串的一部分着色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆