How to set button click effect in Android?

后端 未结 14 2293
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-28 01:29

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.

相关标签:
14条回答
  • 2020-11-28 02:11

    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);
    
    0 讨论(0)
  • 2020-11-28 02:11

    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"
    
    0 讨论(0)
提交回复
热议问题