Android - TextView with different background colors

前端 未结 1 788
名媛妹妹
名媛妹妹 2020-12-18 11:38

Is it possible to have a TextView with different background colors. Eg. If the text is \"This is a test\", is it possible to set different background color for the four word

相关标签:
1条回答
  • 2020-12-18 12:03

    Yes.

    SpannableString spannableString = new SpannableString(getString(R.string.hello_world));
    Object greenSpan = new BackgroundColorSpan(Color.GREEN);
    Object redSpan = new BackgroundColorSpan(Color.RED);
    spannableString.setSpan(greenSpan, 0, 6, 0);
    spannableString.setSpan(redSpan, 6, spannableString.length(), 0);
    
    TextView textView = (TextView) findViewById(R.id.text);
    textView.setText(spannableString);
    

    Produces:

    enter image description here

    EDIT: There are a lot of different spannable types, you can do much nicer looking things than my basic example. Check out this article.

    0 讨论(0)
提交回复
热议问题