Search code examples
androidandroid-radiogroupandroid-radiobutton

Set color text RadioButton checked in RadioGroup with custom Shape


I have a problem, I can't change text color to RadioButton if it's selected. I have this in activity.xml

<RadioGroup
    android:id="@+id/activity_onsite"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true" >
    <RadioButton
        android:id="@+id/onsite_0"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:checked="true"
        android:background="@drawable/toggle_btn"
        android:padding="10dp"
        android:text="office"

        android:button="@null"/>

    <RadioButton
        android:id="@+id/onsite_1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/toggle_btn"
        android:text="clients"
        android:padding="10dp"
        android:button="@null"/>
</RadioGroup>

in my resources @drawable/togglebtn I have

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

And finally in my @drawable/radio_btn_selected

<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<corners
    android:radius="5dp" />
<solid
    android:color="#39b3d7"

    />
<stroke
    android:width="1dp"
    android:color="#269abc" />
</shape>

And in @drawable/radio_btn_regular

<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<corners
    android:radius="5dp" />
<solid
    android:color="#fff"

     />
<stroke
    android:width="1dp"
    android:color="#269abc" />
</shape>

Can I change text color in radio_btn_selected.xml?


Solution

  • You can't set both background & textColor attributes using a single selector. Create a new selector for textColor say radio_text_selected.xml

    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:state_pressed="true" android:color="#39b3d7"/>
        <item android:state_checked="true" android:color="#39b3d7"/>
        <item android:color="#ff8a8a"/>
    </selector>
    

    Set the textColor attribute of RadioButton

    android:textColor="@drawable/radio_text_selected"