How to set button click effect in Android?

后端 未结 14 2362
佛祖请我去吃肉
佛祖请我去吃肉 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 01:57

    It is simpler when you have a lot of image buttons, and you don't want to write xml-s for every button.

    Kotlin Version:

    fun buttonEffect(button: View) {
        button.setOnTouchListener { v, event ->
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    v.background.setColorFilter(-0x1f0b8adf, PorterDuff.Mode.SRC_ATOP)
                    v.invalidate()
                }
                MotionEvent.ACTION_UP -> {
                    v.background.clearColorFilter()
                    v.invalidate()
                }
            }
            false
        }
    }
    

    Java Version:

    public static void buttonEffect(View button){
        button.setOnTouchListener(new OnTouchListener() {
    
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN: {
                        v.getBackground().setColorFilter(0xe0f47521,PorterDuff.Mode.SRC_ATOP);
                        v.invalidate();
                        break;
                    }
                    case MotionEvent.ACTION_UP: {
                        v.getBackground().clearColorFilter();
                        v.invalidate();
                        break;
                    }
                }
                return false;
            }
        });
    }
    

提交回复
热议问题