問(wèn)題描述
在我的應(yīng)用程序中,我需要同時(shí)處理移動(dòng)和點(diǎn)擊事件.
In my application, I need to handle both move and click events.
點(diǎn)擊是一個(gè) ACTION_DOWN 動(dòng)作、幾個(gè) ACTION_MOVE 動(dòng)作和一個(gè) ACTION_UP 動(dòng)作的序列.理論上,如果您收到一個(gè) ACTION_DOWN 事件,然后是一個(gè) ACTION_UP 事件 - 這意味著用戶剛剛單擊了您的視圖.
A click is a sequence of one ACTION_DOWN action, several ACTION_MOVE actions and one ACTION_UP action. In theory, if you get an ACTION_DOWN event and then an ACTION_UP event - it means that the user has just clicked your View.
但實(shí)際上,此序列不適用于某些設(shè)備.在我的三星 Galaxy Gio 上,只需單擊我的視圖就會(huì)得到這樣的序列:ACTION_DOWN,幾次 ACTION_MOVE,然后是 ACTION_UP.IE.我收到一些帶有 ACTION_MOVE 操作代碼的意外 OnTouchEvent 觸發(fā).我從來(lái)沒(méi)有(或幾乎從來(lái)沒(méi)有)得到序列 ACTION_DOWN -> ACTION_UP.
But in practice, this sequence doesn't work on some devices. On my Samsung Galaxy Gio I get such sequences when just clicking my View: ACTION_DOWN, several times ACTION_MOVE, then ACTION_UP. I.e. I get some unexpectable OnTouchEvent firings with ACTION_MOVE action code. I never (or almost never) get sequence ACTION_DOWN -> ACTION_UP.
我也不能使用 OnClickListener,因?yàn)樗鼪](méi)有給出點(diǎn)擊的位置.那么如何檢測(cè)點(diǎn)擊事件并將其與移動(dòng)區(qū)別開(kāi)來(lái)呢?
I also cannot use OnClickListener because it does not gives the position of the click. So how can I detect click event and differ it from move?
推薦答案
這是另一個(gè)非常簡(jiǎn)單的解決方案,不需要您擔(dān)心手指被移動(dòng).如果您將點(diǎn)擊作為簡(jiǎn)單移動(dòng)距離的基礎(chǔ),那么您如何區(qū)分點(diǎn)擊和長(zhǎng)點(diǎn)擊.
Here's another solution that is very simple and doesn't require you to worry about the finger being moved. If you are basing a click as simply the distance moved then how can you differentiate a click and a long click.
您可以在其中添加更多智能并包括移動(dòng)的距離,但我還沒(méi)有遇到一個(gè)實(shí)例,即用戶可以在 200 毫秒內(nèi)移動(dòng)的距離應(yīng)該構(gòu)成移動(dòng)而不是點(diǎn)擊.
You could put more smarts into this and include the distance moved, but i'm yet to come across an instance when the distance a user can move in 200 milliseconds should constitute a move as opposed to a click.
setOnTouchListener(new OnTouchListener() {
private static final int MAX_CLICK_DURATION = 200;
private long startClickTime;
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
startClickTime = Calendar.getInstance().getTimeInMillis();
break;
}
case MotionEvent.ACTION_UP: {
long clickDuration = Calendar.getInstance().getTimeInMillis() - startClickTime;
if(clickDuration < MAX_CLICK_DURATION) {
//click event has occurred
}
}
}
return true;
}
});
這篇關(guān)于onTouchEvent()中如何區(qū)分移動(dòng)和點(diǎn)擊?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!