微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用Android接收onTouch和onClick事件

我有一个视图需要处理onTouch手势和onClick事件.实现这个目标的正确方法是什么?

我在视图上设置了onTouchListener和onClickListener.每当我触摸视图时,首先触发onTouch事件,然后触发onClick.但是,从onTouch事件处理程序我必须返回true或false.返回true表示正在使用该事件,因此android事件系统不会再传播该事件.

因此,永远不会生成onClick事件,至少在我的onTouch事件处理程序中返回true时,我的onClick侦听器永远不会被触发.另一方面,返回false则没有选项,因为这会阻止onTouch侦听器接收识别手势所需的任何其他事件.解决这个问题的常用方法是什么?

解决方法

在你的GestureDetector中,你可以直接调用callOnClick().
请注意,View.callOnClick API需要API级别15.
试一试.
// Create a Gesturedetector
GestureDetector mGestureDetector = new GestureDetector(context,new MyGestureDetector());

// Add a OnTouchListener into view
m_myViewer.setonTouchListener(new OnTouchListener()
{

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

private class MyGestureDetector extends GestureDetector.SimpleOnGestureListener
{
    public boolean onSingleTapUp(MotionEvent e) {
        // ---Call it directly---
        callOnClick();
        return false;
    }

    public void onLongPress(MotionEvent e) {
    }

    public boolean onDoubleTap(MotionEvent e) {
        return false;
    }

    public boolean onDoubleTapEvent(MotionEvent e) {
        return false;
    }

    public boolean onSingleTapConfirmed(MotionEvent e) {
        return false;

    }

    public void onShowPress(MotionEvent e) {
        LogUtil.d(TAG,"onShowPress");
    }

    public boolean onDown(MotionEvent e) {            
        // Must return true to get matching events for this down event.
        return true;
    }

    public boolean onScroll(MotionEvent e1,MotionEvent e2,final float distanceX,float distanceY) {
        return super.onScroll(e1,e2,distanceX,distanceY);
    }        

    @Override
    public boolean onFling(MotionEvent e1,float veLocityX,float veLocityY) {
        // do something
        return super.onFling(e1,veLocityX,veLocityY);
    }
}

原文地址:https://www.jb51.cc/android/316734.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐