Set color of TextView span in Android

前端 未结 15 1686
眼角桃花
眼角桃花 2020-11-22 05:54

Is it possible to set the color of just span of text in a TextView?

I would like to do something similar to the Twitter app, in which a part of the text is blue. See

15条回答
  •  一个人的身影
    2020-11-22 06:22

    I always find visual examples helpful when trying to understand a new concept.

    Background Color

    SpannableString spannableString = new SpannableString("Hello World!");
    BackgroundColorSpan backgroundSpan = new BackgroundColorSpan(Color.YELLOW);
    spannableString.setSpan(backgroundSpan, 0, spannableString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    textView.setText(spannableString);
    

    Foreground Color

    SpannableString spannableString = new SpannableString("Hello World!");
    ForegroundColorSpan foregroundSpan = new ForegroundColorSpan(Color.RED);
    spannableString.setSpan(foregroundSpan, 0, spannableString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    textView.setText(spannableString);
    

    Combination

    SpannableString spannableString = new SpannableString("Hello World!");
    ForegroundColorSpan foregroundSpan = new ForegroundColorSpan(Color.RED);
    BackgroundColorSpan backgroundSpan = new BackgroundColorSpan(Color.YELLOW);
    spannableString.setSpan(foregroundSpan, 0, 8, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    spannableString.setSpan(backgroundSpan, 3, spannableString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    textView.setText(spannableString);
    

    Further Study

    • Explain the meaning of Span flags like SPAN_EXCLUSIVE_EXCLUSIVE
    • Android Spanned, SpannedString, Spannable, SpannableString and CharSequence

提交回复
热议问题