Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android background that ripples when pressed, but solid color when selected?

I'm trying to create a drawable that ripples when it's pressed, but when view.setSelected(true) is called, it holds a solid color for a background.

The following file is placed in my drawable-v21 folder:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_selected="true">
        <color android:color="@color/green_primary" />
    </item>

    <item android:state_pressed="true">
        <ripple android:color="@color/green_primary">
            <item android:id="@android:id/mask">
                <shape android:shape="rectangle">
                    <solid android:color="@color/green_selected" />
                </shape>
            </item>
        </ripple>
    </item>
</selector>

I've tried the above, and it holds a solid background when it's selected, but there isn't a ripple effect, rather just kind of a fade-in effect. If I just have the ripple with no selector, it ripples correctly when pressed, but obviously then I don't have a selected state. How could I have both baked into a single background drawable?

like image 641
spierce7 Avatar asked May 09 '15 06:05

spierce7


People also ask

What is ripple color Android?

As you've noticed, ripples are used subtle indications of touch feedback, hence why they do not use colorPrimary or colorAccent by default. This is consistent with the changes made in Android 4.4 (Kitkat) which made the default selector colors neutral by default.

What is ripple effect in Android?

Ripple touch effect was introduced with material design in Android 5.0 (API level 21). Touch feedback in material design provides an instantaneous visual confirmation at the point of contact when users interact fwith UI elements.


1 Answers

What you need to do is:

1. Create a ripple_effect.xml file in drawable-v21 folder

<ripple xmlns:android="http://schemas.android.com/apk/res/android"
        android:color="@color/green_primary">
    <item android:drawable="@drawable/green_primary"/>
</ripple>

2. Create button_selector.xml file in drawable folder to set the selected state color.

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_selected="true"
            android:drawable="@color/green_selected"/>
    <item android:drawable="@drawable/ripple_effect"/>
</selector>
like image 77
iMDroid Avatar answered Nov 11 '22 09:11

iMDroid