问题描述
在我的应用程序,我需要同时处理移动和点击的事件。
In my application, I need to handle both move and click events.
一个点击是一个ACTION_DOWN行动,几个ACTION_MOVE动作和一个ACTION_UP动作序列。从理论上讲,如果你得到一个ACTION_DOWN事件,然后一个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.
但是,在实践中,这一序列不某些设备上工作。在我的三星Galaxy吉奥我得到这样的序列时,只需点击我的看法:ACTION_DOWN,几次ACTION_MOVE,然后ACTION_UP。即我得到一些不可预料的onTouchEvent生火用ACTION_MOVE行动code。我从来没有(或几乎没有)获得序列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,因为它不给出的点击的位置。所以,我怎么能检测单击事件,并从不同的举动呢?
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?
推荐答案
下面是另一种解决方案,这是非常简单的,不需要你担心手指被移动。如果你是立足点击为简单移动的距离,那么你怎么能区分一个点击和长按。
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.
您可以把更多的智慧到这一点,包括移动的距离,但我还没有碰到过一个实例时的距离,用户可以在200毫秒内移动应构成一个举动,而不是点击。
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;
}
});
这篇关于如何移动进行区分,并且点击的onTouchEvent()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!