在android中使用不同颜色的单词自定义TextView

时间:2012-07-13 23:22:10

标签: android textview

是否可以让textview为每个单词设置不同的颜色?甚至每封信?我尝试扩展textview并创建它但是我想到的问题是,我如何用不同的颜色同时绘制所有文本?

3 个答案:

答案 0 :(得分:27)

使用android.text.Spannable

final SpannableStringBuilder str = new SpannableStringBuilder(text);
str.setSpan(
    new ForegroundColorSpan(Color.BLUE), 
    wordStart, 
    wordEnd, 
    SpannableStringBuilder.SPAN_EXCLUSIVE_EXCLUSIVE
);
myTextView.setText(str);

编辑:使所有“Java”变为绿色

final Pattern p = Pattern.compile("Java");
final Matcher matcher = p.matcher(text);

final SpannableStringBuilder spannable = new SpannableStringBuilder(text);
final ForegroundColorSpan span = new ForegroundColorSpan(Color.GREEN);
while (matcher.find()) {
    spannable.setSpan(
        span, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
    );
}
myTextView.setText(spannable);

答案 1 :(得分:19)

SpannableString类允许您通过ForegroundColorSpan方法通过应用CharacterStyle(即setSpan)的扩展,轻松地格式化字符串的某些片段(跨度)以及其他片段

你可以试试这个:

@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);
    richTextView = (TextView)findViewById(R.id.rich_text);

    // this is the text we'll be operating on
    SpannableString text = new SpannableString("Lorem ipsum dolor sit amet");

    // make "Lorem" (characters 0 to 5) red
    text.setSpan(new ForegroundColorSpan(Color.RED), 0, 5, 0);

    // make "ipsum" (characters 6 to 11) one and a half time bigger than the textbox
    text.setSpan(new RelativeSizeSpan(1.5f), 6, 11, 0);

    // make "dolor" (characters 12 to 17) display a toast message when touched
    final Context context = this;
    ClickableSpan clickableSpan = new ClickableSpan() {
        @Override
        public void onClick(View view) {
            Toast.makeText(context, "dolor", Toast.LENGTH_LONG).show();
        }
    };
    text.setSpan(clickableSpan, 12, 17, 0);

    // make "sit" (characters 18 to 21) struck through
    text.setSpan(new StrikethroughSpan(), 18, 21, 0);

    // make "amet" (characters 22 to 26) twice as big, green and a link to this site.
    // it's important to set the color after the URLSpan or the standard
    // link color will override it.
    text.setSpan(new RelativeSizeSpan(2f), 22, 26, 0);
    text.setSpan(new URLSpan("http://www.chrisumbel.com"), 22, 26, 0);
    text.setSpan(new ForegroundColorSpan(Color.GREEN), 22, 26, 0);

    // make our ClickableSpans and URLSpans work
    richTextView.setMovementMethod(LinkMovementMethod.getInstance());

    // shove our styled text into the TextView        
    richTextView.setText(text, BufferType.SPANNABLE);
}

结果如下:

enter image description here

有关详细信息,请参阅Chris Umbel blog

答案 2 :(得分:4)

是的,您可以使用SpannableSpannableStringBuilder执行此操作。有关示例,请参阅Is there any example about Spanned and Spannable text

有关格式化文本的各种方法(背景颜色,前景色,可点击等),请参阅CharacterStyle