Search code examples
androidradio-buttonmaterial-designselectorandroid-drawable

Can i change radio button drawable in android for API < 21?


I am using AppCompatRadioButton and i want to use my custom drawable for that and i achieved this via code below but its working only for API >= 21.

 <android.support.v7.widget.AppCompatRadioButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

selector_custom_radio_buttons.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:drawable="@drawable/ic_done_single" android:state_checked="false" />
<item android:drawable="@drawable/ic_done_all" android:state_checked="true" />
</selector>

and then i set the radio buttons selector via style in activity theme

Styles.xml

  <!-- Base application theme. -->
<style name="ThemeNewsFeed" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="android:radioButtonStyle">@style/MyRadioButtonStyle</item>
</style>

<style name="MyRadioButtonStyle">
    <item name="android:button">@drawable/selector_custom_radio_buttons</item>
</style>

and here is activity in AndroidManifest.xml

<activity android:name=".social.NewsFeedActivity"
        android:theme="@style/ThemeNewsFeed">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>

    </activity>

Note: The problem is my custom drawable are working well on API 21 and greater but on API less then 21 , its showing default radio buttons drawable. so what should i do for lower API's ?


Solution

  • Just Remove your AppCompatRadioButton style from activity theme and set directly to AppCompatRadioButton xml code like below

     <android.support.v7.widget.AppCompatRadioButton
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         style="@style/MyRadioButtonStyle""/>
    

    and in Style.xml

     <style name="MyRadioButtonStyle" parent="@android:style/Widget.CompoundButton.RadioButton">
            <item name="android:button">@drawable/selector_custom_radio_buttons</item>
        </style>