This is the best solution I came up with to get hints from @Vinayak's answer. All other solutions have different disadvantages.
First of all, create such a function.
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 an existing Drawable, otherwise the same drawable will be used. Read more here: Android: clone selected file to make StateListDrawable with filters
mutate () is used to make Drawable clone not sharing its state with other Drawable instances. More about this here: https://developer.android.com/reference/android/graphics/drawable/Drawable.html#mutate ()
Application:
As a parameter to a function, you can pass any types of View (Button, ImageButton, View, etc.), and they will get the click effect applied to them.
addClickEffect(myButton); addClickEffect(myImageButton);
Ehtesham Hasan Sep 10 '16 at 21:29 2016-09-10 21:29
source share