最近在項目中需要對一個按鈕實現(xiàn)短按和長按的事件處理末盔,總結了一下常規(guī)的寫法
思路就是:
1 key_down時開始計時長按所需的時間
2 key_up時判斷是否執(zhí)行了長按的操作筑舅,如果未執(zhí)行座慰,那么執(zhí)行短按操作陨舱,同時取消長按計時
/**
* 是否長按
*/
private boolean hasLongPress = false;
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
/*
* 按下開始執(zhí)行長按計時
*/
mHandler.sendEmptyMessageDelayed(0, 1000);
return true;
} else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
mHandler.removeMessages(0);
/*如果還未執(zhí)行長按,那么執(zhí)行短按事件*/
if (!hasLongPress) {
doSingleClick();
}
hasLongPress = false;
return true;
}
return false;
}
private final Handler mHandler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
if (msg.what == 0) {
hasLongPress = true;
doLongClick();
}
}
};
private void doLongClick() {
}
private void doSingleClick() {
}