长按安卓系统

10

我在自定义视图中检测长按时遇到了问题。

以下是与此问题相关的代码:

final GestureDetector gestureDetector = new GestureDetector(new GestureDetector.SimpleOnGestureListener() {
    public void onLongPress(MotionEvent e) {
        Log.e("dbg_msg", "onLongPress");
    }
});

public boolean onTouchEvent(MotionEvent event) {
    return gestureDetector.onTouchEvent(event);
};

这段代码将每次短按都识别为长按。

当我把这段代码放在从Activity继承来的类中时,它有效运行。

那么为什么在自定义视图中它没有效果呢?


从onTouchEvent返回true解决了我的问题。 - Manuel
4个回答

25

这段代码都应该放在你自定义视图类中:

public static int LONG_PRESS_TIME = 500; // Time in miliseconds 

final Handler _handler = new Handler(); 
Runnable _longPressed = new Runnable() { 
    public void run() {
        Log.i("info","LongPress");
    }   
};

@Override
public boolean onTouchEvent(MotionEvent event) {
    switch(event.getAction()){
    case MotionEvent.ACTION_DOWN:
        _handler.postDelayed(_longPressed, LONG_PRESS_TIME);
        break;
    case MotionEvent.ACTION_MOVE:
        _handler.removeCallbacks(_longPressed);
        break;
    case MotionEvent.ACTION_UP:
        _handler.removeCallbacks(_longPressed);
        break;
    }
    return true;
}

1
还应该在 MotionEvent.ACTION_CANCEL 上调用 removeCallbacks。 - kasgoku
2
你应该移除ACTION_MOVE,因为它会取消处理程序。 - Marian Pavel

4
我不确定,但是您的GestureDetector构造函数已过时(这里)。您可以尝试其他需要上下文作为第一个参数的构造函数吗?
抱歉,我是新手,无法发布评论。
已编辑
似乎您使用了另一个侦听器,这个View.OnTouchListener有其他onTouch()方法。您可以再试一次吗?
已编辑
这是一个示例(对我有用):
...
mAnotherView.setOnTouchListener(new View.OnTouchListener() {

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        return mGestureDetector.onTouchEvent(event);
    }
});

...
mGestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {

    @Override
    public void onLongPress(MotionEvent e) {
        // do your tasks here
    }
});

怎么做,我不明白你的意思? - Nikola Ninkovic
1
不客气 :-) 我认为你可以自己回答,这样有助于其他人阅读你的问题。 - Anh3Saigon
请接受您的答案(提示)。抱歉我说了这么多... - Anh3Saigon
没关系,我必须等待48小时才能这样做 :) - Nikola Ninkovic

4

您是否在GestureDetector上启用了长按? 您可以通过使用适当的构造函数或调用setIsLongpressEnabled来启用它。例如,您可以执行以下操作:

gestureDetector.setIsLongpressEnabled(true);

在你的构造函数中。


0

我猜应该会更好吧..

public class Workflow extends View implements View.OnLongClickListener {

public Workflow(Context context, DisplayFeatures d) {
    super(context);

    setLongClickable(true);
    setOnLongClickListener(this);
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    /* onTouchEvent should return super.onTouchEvent(event);, otherwise long click wouldn't be performed */
    return super.onTouchEvent(event);
}

@Override
public boolean onLongClick(View v) {
    Log.d("VIEW", "LONG CLICK PERFORMED!");
    return false;
}
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接