使用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);
    }
}

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...