Ripple effect inside of a selector

4.7k views Asked by At

I would like to achieve a ripple effect when someone presses my ImageView, but also have different drawables for other states.

I have a very simple ImageView:

<ImageView
    android:id="@+id/image"
    android:layout_width="120dp"
    android:layout_height="120dp"
    android:clickable="true"
    />

I add my background to it:

mImage.setBackgroundResource(R.drawable.background_resource);

My drawable looks like this:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_selected="false">
        <shape
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:shape="oval">

            <solid
                android:color="@android:color/darker_gray"/>

            <size
                android:width="80dp"
                android:height="80dp"/>
        </shape>
    </item>
    <item android:state_selected="true" android:state_pressed="false">
        <shape
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:shape="oval">

            <solid
                android:color="@android:color/holo_blue_bright"/>

            <size
                android:width="120dp"
                android:height="120dp"/>
        </shape>
    </item>
    <item android:state_pressed="true">
        <ripple android:color="@android:color/holo_blue_dark">
            <item android:id="@android:id/mask">
                <shape android:shape="oval">

                    <solid android:color="@android:color/holo_blue_dark"/>

                    <size
                        android:width="120dp"
                        android:height="120dp"/>
                </shape>
            </item>
        </ripple>
    </item>
</selector>

When I click, the background disappears instead of showing the ripple effect. The other states work fine. Any idea what I am doing wrong here?

2

There are 2 answers

1
Avinash R On

It turns out you've got it the other way, in order for the ripple to show up, you need to include the selector inside the ripple drawable

i.e., the xml should be looking like

<ripple android:color="@color/ripple_color">
    <item android:id="@android:id/mask">
        <!-- ripple mask goes here -->
    </item>
    <item>
        <selector>
            <!-- your selector goes here -->
        </selector>
    </item>
</ripple>

HTH.

1
Wez On

Have a look at this example of a RelativeLayout which draws a ripple effect on top of the view when it is pressed:

RippleEffect.java