Set color of TextView span in Android

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

    Here is a little help function. Great for when you have multiple languages!

    private void setColor(TextView view, String fulltext, String subtext, int color) {
        view.setText(fulltext, TextView.BufferType.SPANNABLE);
        Spannable str = (Spannable) view.getText();
        int i = fulltext.indexOf(subtext);
        str.setSpan(new ForegroundColorSpan(color), i, i + subtext.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
    

提交回复
热议问题