Search code examples
androidandroid-radiobutton

Android: Specifying style of programmatically added radio buttons when focused


I'm working on my first Android app, and I've run into a bit of a problem concerning the appearance. I'm programmatically adding radio buttons to a radio group defined in a linear layout. I'm using a dark theme, and when any of the elements defined in the layout gain focus, they are highlighted in a yellow color: a button with focus has an overall yellow highlight, while a checkbox with focus has yellow text. But for the dynamically-added radio buttons, when the radio button gains focus the text changes to black (the same as the background).

How do I either specify that the dynamically added radio buttons use the same style on focus as the other elements, or else specify a custom on-focus style for theme?

Here's the code I'm using to add the radio buttons:

RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radioGroupVersions);
RadioGroup.LayoutParams rprms;

for(int i=0;i<installedVersionName.size();i++)
{
    RadioButton radioButton = new RadioButton(this);
    radioButton.setText(installedVersionName.get(i));
    radioButton.setId(i);
    rprms = new RadioGroup.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    radioGroup.addView(radioButton, rprms);
}

I haven't changed anything about the appearance except setting android:background="@color/black" for the LinearLayout to provide a solid background instead of the gradient used by the theme.


Solution

  • You can use TextView.setTextColor(ColorStateList) to achieve this.

    To create a ColorStateList, just initialize with the different "cases" for the combinations of state flags that you are interested in. For example:

    ColorStateList colors = new ColorStateList(
        new int[][] {
            new int [] { android.R.attr.state_pressed },
            new int [] { android.R.attr.state_selected },
            new int[0],
        },
        new int[] {
            highlightedColor,
            highlightedColor,
            color,
        });
    
    tv.setTextColor(colors);
    

    This would use "color" for the normal state, and "highlightedColor" when the TextView is pressed or selected. For a list of the possible states, see R.attr. You are probably interested in state_checked but I haven't tested that case.