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

时间:2016-06-17 13:01:52

标签: android

我的XML活动布局中有一个按钮,它使用蓝色或红色png图像作为背景(这是在打开活动之前设置的)

当以编程方式按下时,如何使其变为灰色(蓝色png必须变为灰色),而不使用状态可绘制。

2 个答案:

答案 0 :(得分:3)

您可以将饱和度为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;
    }
});

答案 1 :(得分:1)

您可以在触摸列表器上使用,请在下面查看您需要根据您的要求修改的示例。

 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;
        }
    });
相关问题