Skip to content
Advertisement

How can I change the drawable color of RadioButton’s background programmatically?

My radio buttons have background which is selector drawable.

And I want to change the color of state_checked=”true” item’s drawable programmatically.

The background of radiobutton :

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="false"
        android:drawable="@drawable/checkbox_membertag_inactive" />
    <item android:state_checked="true"
        android:drawable="@drawable/checkbox_membertag_active"/>
</selector>

checkbox_membertag_active :

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <stroke
        android:width="1dp"
        android:color="@color/white" />
    <corners
        android:radius="36dp" />
    <solid
        android:color="@color/white" />
</shape>

and I tried in this way. I want to change the @color/white of active item to starColor which I pre-declared. But it’s still white color.

rgEventStyle.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @SuppressLint("ResourceAsColor")
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton checkedEvtStyle = findViewById(checkedId);
                StateListDrawable stateListDrawable = (StateListDrawable) checkedEvtStyle.getBackground();
                stateListDrawable.addState(new int[]{android.R.attr.state_checked},new ColorDrawable(starColor));
                stateListDrawable.addState(new int[]{-android.R.attr.state_checked}, new ColorDrawable(R.color.gray5));
                checkedEvtStyle.setBackground(stateListDrawable);
            }
        });

Advertisement

Answer

Try with ColorStatList like the Code below :

rgEventStyle.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @RequiresApi(api = Build.VERSION_CODES.M)
        @SuppressLint("ResourceAsColor")
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {

            int[][] state =
                    {
                            new int[]{android.R.attr.state_checked},
                            new int[]{-android.R.attr.state_checked}
                    };
            int[] color = new int[]
                    {
                            ContextCompat.getColor(getApplicationContext(), R.starColor),
                            ContextCompat.getColor(getApplicationContext(), R.color.gray5)
                    };
            RadioButton checkedEvtStyle = findViewById(checkedId);
            ColorStateList colorStateList = new ColorStateList(state, color);
            checkedEvtStyle.setBackgroundTintList(colorStateList);
        }
    });
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement