setOnCheckedChangeListener for every radiobutton

129 Views Asked by At

I have a radiogroup containing several radiobuttons whose background color is grey. When I click on a radiobutton I would need the clicked one to change background color to black, while others would keep the grey background. I know I can set OnCheckedChangeListeners for all radiobuttons like this:

if(checked) then setBackGroundColor to black;

else setBackGroundColor to grey;

but is there any more efficient way to do that? Like write just one OnCheckedChangeListener for the whole group

1

There are 1 best solutions below

0
avalerio On

Create a selector -> drawable/radio_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true"
        android:color="@color/black" /> <!-- checked -->
    <item android:state_checked="false"
        android:color="@color/grey" /> <!-- unchecked -->
</selector>

And in the RadioButton view add

android:buttonTint="@drawable/radio_selector"

This works on api 21+ If you are using a lower minimum api you will need to set buttonTint in a style

   <style name="radio_style" parent="Widget.AppCompat.CompoundButton.RadioButton">
       <item name="buttonTint">@drawable/radio_selector</item>
   </style>

and add this instead to your RadionButton

style="@style/radio_style"