Search code examples
androidxmlandroid-5.0-lollipop

Ripple effect on shape drawable


Trying to do something really simple here and have looked up a bunch of SO resource, but to no avail. I am trying to get the ripple effect on a button which uses a drawable background of type of shape drawable. The relevant files:

background_button:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <stroke
        android:width="1px"
        android:color="#80ffffff" />
    <solid android:color="@android:color/transparent" />
</shape>

ripple.xml within the drawable-v21 folder:

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

Button.xml:

   <Button
                    android:id="@+id/login_button"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="20dp"
                    android:layout_weight="1"
                    android:paddingTop="10dp"
                    android:paddingBottom="10dp"
                    android:background="@drawable/ripple"


 />

What is wrong here. Thanks!


Solution

  • My advice would be not to use <ripple tag. I have 2 reasons: it is not that easy to do exactly what you want and you have to 2 different .xml files for every background. I don't like to have drawable-v21 folder.

    My solution is to wrap your Button with FrameLayout and use android:foreground attribute. This way you can have whatever background you want and you can keep the ripple effect.

    <FrameLayout
        android:id="@+id/login_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:layout_weight="1"
        android:paddingTop="10dp"
        android:paddingBottom="10dp"
        android:foreground="?attr/selectableItemBackground">
    
        <Button
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/background_button"/>
    </FrameLayout>
    

    Notice that I moved all the attributes and the id to FrameLayout. You should set onClickListener to FrameLayout instead of the Button.

    Btw, ?attr/selectableItemBackground is great. Use it as much as possible. It replaces blue Holo color with gray for old devices from Android 4.0 to 4.3.