-1

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

Tam Nguyen
  • 25
  • 5
  • I thought there was one listener for the whole group. – blackapps May 27 '21 at 17:16
  • you also try like this in your design https://stackoverflow.com/a/67724183/8133524 or `id.setBackgroundColor(getResources().getColor(R.color.Black));` – Ramesh May 27 '21 at 17:20

1 Answers1

0

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"
avalerio
  • 2,072
  • 1
  • 12
  • 11