[英]How can I change button color (png) when pressed down programmatically?
我的XML活动布局中有一个按钮,该按钮使用蓝色或红色png图像作为背景(在打开活动之前进行了设置)
如何以编程方式按下时使其变为灰色(蓝色png必须变为灰色),而不使用可绘制状态。
您可以为按钮背景设置一个饱和度为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;
}
});
您可以在触摸列表器上使用它,请仅在下面查看需要根据需要进行修改的示例。
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.