Search code examples
androidandroid-layoutandroid-radiobutton

Android: set background color of radiobutton text programatically


When i try to change background color of radio button text programatically like this:

rb.setBackgroundResource(R.drawable.mycustombackground);

The background covers both the button and the text.
I only want to change the background color of the text part (not the radio button).

How to achieve that?


Solution

  • Ok, lets see if it works:

    Spannable span = new SpannableStringBuilder(rb.getText().toString());
    span.setSpan(new BackgroundColorSpan(Color.RED), 0, rb.getText().toString().length(), SpannableStringBuilder.SPAN_INCLUSIVE_INCLUSIVE);
    rb.setText(span);
    

    Replace Color.RED with whichever color you want. Don't forget you have to grab it from the resources if you want it. I don't think it works with drawables.