In Android, when I set background image to Button, I can not see any effect on button.
I need some effect on button so user can recognize that button is clicked.
This is the best solution I came up with taking hints from @Vinayak's answer. All the other solutions have different drawbacks.
First of all create a function like this.
void addClickEffect(View view)
{
Drawable drawableNormal = view.getBackground();
Drawable drawablePressed = view.getBackground().getConstantState().newDrawable();
drawablePressed.mutate();
drawablePressed.setColorFilter(Color.argb(50, 0, 0, 0), PorterDuff.Mode.SRC_ATOP);
StateListDrawable listDrawable = new StateListDrawable();
listDrawable.addState(new int[] {android.R.attr.state_pressed}, drawablePressed);
listDrawable.addState(new int[] {}, drawableNormal);
view.setBackground(listDrawable);
}
Explanation:
getConstantState().newDrawable() is used to clone the existing Drawable otherwise the same drawable will be used. Read more from here: Android: Cloning a drawable in order to make a StateListDrawable with filters
mutate() is used to make the Drawable clone not share its state with other instances of Drawable. Read more about it here: https://developer.android.com/reference/android/graphics/drawable/Drawable.html#mutate()
Usage:
You can pass any type of View (Button, ImageButton, View etc) as the parameter to the function and they will get the click effect applied to them.
addClickEffect(myButton);
addClickEffect(myImageButton);
For all the views
android:background="?android:attr/selectableItemBackground"
But for cardview which has elevation use
android:foreground="?android:attr/selectableItemBackground"
For Circular click effect as in toolbar
android:background="?android:attr/actionBarItemBackground"
Also you need to set
android:clickable="true"
android:focusable="true"