简体   繁体   English

以编程方式按下时如何更改按钮颜色(png)?

[英]How can I change button color (png) when pressed down programmatically?

I have a button in my XML activity layout that uses either a blue or a red png image as its background (this is set up before opening the activity) 我的XML活动布局中有一个按钮,该按钮使用蓝色或红色png图像作为背景(在打开活动之前进行了设置)

How do I make it turn gray (the blue png has to become gray) when pressed programmatically, without using a state drawable. 如何以编程方式按下时使其变为灰色(蓝色png必须变为灰色),而不使用可绘制状态。

You can set a ColorMatrixColorFilter with a saturation of 0 to the button background: 您可以为按钮背景设置一个饱和度为0的ColorMatrixColorFilter

final Button mybutton = (Button) findViewById(R.id.mybutton);
mybutton.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(final View view, final MotionEvent motionEvent) {
        if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
            final ColorMatrix matrix = new ColorMatrix();
            matrix.setSaturation(0);
            mybutton.getBackground().setColorFilter(new ColorMatrixColorFilter(matrix));
        } else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
            final ColorMatrix matrix = new ColorMatrix();
            matrix.setSaturation(1);
            mybutton.getBackground().setColorFilter(new ColorMatrixColorFilter(matrix));
        }
        return true;
    }
});

You can use on touch listner for that, check below for just example which you need to modify as per your requirement. 您可以在触摸列表器上使用它,请仅在下面查看需要根据需要进行修改的示例。

 button.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN)
            {                    
                button.setBackgroundColor(Color.GRAY);
            }
            else if (event.getAction() == MotionEvent.ACTION_UP)
            {                    
                button.setBackgroundColor(Color.RED);
            }

            return false;
        }
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM