androidandroid-layoutandroid-buttonrippledrawable

Android: Button with Ripple and State Selector in Background: Resource Not Found Exception


I have a button with a ripple effect and would like to add a state selector for the background color when the button is enabled/disabled.

state_selector.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:color="@color/green" android:state_enabled="true"/>

    <item android:color="@color/grey" android:state_enabled="false"/>

</selector>

ripple.xml:

<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="?android:colorControlHighlight"> 
    <item android:id="@android:id/mask" android:drawable="@android:color/white" />

    <item android:id="@android:id/background" android:drawable="@drawable/state_selector" />

</ripple>

Button.xml:

<Button
        android:background="@drawable/ripple"
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
         />

But the app crashes while rendering this with the following:

Resources$NotFoundException: Drawable drawable/ripple with resource ID #0x7f070071
     Caused by: android.content.res.Resources$NotFoundException: File res/drawable/ripple.xml from drawable resource ID #0x7f070071

and

android.content.res.Resources$NotFoundException: Drawable drawable/state_selector with resource ID #0x7f070075
     Caused by: android.content.res.Resources$NotFoundException: File res/drawable/state_selector.xml from drawable resource ID #0x7f070075

could someone please help figure out the issue? thanks


Solution

  • I found the issue.

    The ripple needs a drawable resource.

    The state selector which I had used did not provide a drawable for each state but rather it provided a color for each state. And thus it was crashing.

    The following xml for the state selector would fix this issue. Everything else remains the same.

    <selector xmlns:android="http://schemas.android.com/apk/res/android">
    
        <item android:drawable="@color/green" android:state_enabled="true"/>
    
        <item android:drawable="@color/grey" android:state_enabled="false"/>
    
    </selector>