Set color of TextView span in Android

前端 未结 15 1817
眼角桃花
眼角桃花 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:32

    String text = "I don't like Hasina.";
    textView.setText(spannableString(text, 8, 14));
    
    private SpannableString spannableString(String text, int start, int end) {
        SpannableString spannableString = new SpannableString(text);
        ColorStateList redColor = new ColorStateList(new int[][]{new int[]{}}, new int[]{0xffa10901});
        TextAppearanceSpan highlightSpan = new TextAppearanceSpan(null, Typeface.BOLD, -1, redColor, null);
    
        spannableString.setSpan(highlightSpan, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(new BackgroundColorSpan(0xFFFCFF48), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(new RelativeSizeSpan(1.5f), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    
        return spannableString;
    }
    

    Output:

提交回复
热议问题