Android Button With Background Color And Ripple Effect

Manish picture Manish · May 13, 2016 · Viewed 11k times · Source

I have an android button, where I want to give it a background color and both ripple effect

my ripple xml is as below.

<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:color="#BDA0CB"
    tools:targetApi="lollipop">
    <item android:id="@android:id/mask">
        <shape android:shape="rectangle">
            <solid android:color="#BDA0CB" />
        </shape>
    </item>
</ripple>

and my button is

 <Button android:id="@+id/Button_activity_login_ViewProfile" style="?android:textAppearanceSmall"
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:layout_marginTop="16dp" android:text="Save"
        android:textStyle="bold"
        android:layout_marginLeft="@dimen/margin_left"
        android:layout_marginRight="@dimen/margin_right"
        android:textColor="#ffffffff"
        android:fontFamily="sans-serif"
        android:background="#ff7e51c2" />

To give the ripple effect I have to remove background color...Is there a way I can keep both.

Answer

James Baltar picture James Baltar · May 13, 2016

This can be achieve by adding the android:drawable in your ripple.xml.

First add this to your color.xml. Assuming that #ff7e51c2 is the background color you want for your button.

...
<color name="btn_bg_color">#ff7e51c2</color>
....

Then create a drawable for the button background(/drawable/btn_bg.xml):

<?xml version="1.0" encoding="utf-8"?><shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<corners android:radius="2dp" />
<solid
    android:color="@color/btn_bg_color" />
</shape>

Then use the drawable in your 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:drawable="@drawable/btn_bg"/>
</ripple>