做法是為控件掛上 OnTouchListener,在 ACTION_DOWN 時給背景套一層半透明色濾鏡,抬手或取消時再清掉。注意控件在 XML 中必須先設定 background,否則拿不到 Drawable 就直接返回。
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;
}
});
這裡有兩個容易忽略的細節:mutate() 只在 1.6 以上需要呼叫,用來避免共用 Drawable 狀態互相污染;透明度值(此處是 100)可依設計稿自行微調。