Ripple Drawables.
Touch feedback in material design provides an instantaneous visual confirmation at the point of contact when users interact with UI elements. The default touch feedback animations for buttons use the new RippleDrawable class, which transitions between different states with a ripple effect.
We can either apply RippleDrawable in XML or using Drawable XML or using java.
Using XML
create a file named “ripple.xml” in the drawable folder
<?xml version="1.0" encoding="utf-8"?> <ripple xmlns:android="http://schemas.android.com/apk/res/android" android:color="?android:colorControlHighlight" />
Ripple animation extends beyond the bounds of its view, i.e the animation goes beyond the view to which it is applied, We will try to set the animation inside the View using the following methods.
Modify the ripple.xml like this.
<?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"> <shape android:shape="rectangle"> <solid android:color="?android:colorAccent" /> </shape> </item> </ripple>
and Apply it as background of your View like this.
<Button android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/tv" android:background="@drawable/ripple" android:text="Button with Ripple Effect BorderLess" />
Another way to set the Ripple Effect within the View is to make a shape drawable and remove the “@android:id/mask”.
<?xml version="1.0" encoding="utf-8"?> <ripple xmlns:android="http://schemas.android.com/apk/res/android" android:color="?android:colorControlHighlight"> <item> <shape android:shape="rectangle"> <stroke android:color="?android:colorAccent" android:width="1dp" /> </shape> </item> </ripple>
Java methods to attain Ripple Effect in Views.
1. Method 1
Button btn = (Button) findViewById(R.id.btn1); RippleDrawable ripple = (RippleDrawable) btn.getBackground(); GradientDrawable rippleBackground = (GradientDrawable) ripple.getDrawable(0); rippleBackground.setColor(Color.GREEN); ripple.setColor(ColorStateList.valueOf(Color.RED));
2. Method 2
Button btn2 = (Button) findViewById(R.id.btn2); Drawable myIcon = getResources().getDrawable(R.drawable.btn2); RippleDrawable rippleDrawable = new RippleDrawable(new ColorStateList(new int[][]{{}}, new int[]{Color.GREEN}), myIcon, null); btn2.setBackground(rippleDrawable);
3. Method 3
Button btn3 = (Button) findViewById(R.id.btn3); rippleDrawable = new RippleDrawable(ColorStateList.valueOf(Color.RED), myIcon, null); btn3.setBackground(rippleDrawable);
4. Method 4
Button btn4 = (Button) findViewById(R.id.btn4); RippleDrawable mRipple = new RippleDrawable(new ColorStateList( new int[][]{ {} }, new int[]{ Color.WHITE }), new ColorDrawable(Color.GREEN), null); btn4.setBackground(mRipple);
You can download the complete Android Studio Source Code from here.