控件设置OnTouchListener,代码如下(控件在xml中需要设置background):
btn.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
Drawable drawable = v.getBackground();
if (drawable == null)
return false;
if (Integer.parseInt(Build.VERSION.SDK) > Build.VERSION_CODES.DONUT)// 1.6版本以上使用
{
drawable.mutate();
}
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
drawable.setColorFilter(Color.argb(100, 0, 0, 0), Mode.DST_IN); //此处值可自行调整
v.setBackgroundDrawable(drawable);
break;
case MotionEvent.ACTION_UP:
drawable.clearColorFilter();
v.setBackgroundDrawable(drawable);
break;
case MotionEvent.ACTION_CANCEL:
drawable.clearColorFilter();
v.setBackgroundDrawable(drawable);
break;
default:
break;
}
return false;
}
});