为填充按钮的衬垫布局添加触摸侦听器



我在线性布局中添加了一个触摸事件来响应滑动手势,效果很好。但是,当我向布局添加按钮时,父衬垫布局将被忽略。我应该如何防止这种情况发生?

LinearLayout ln2 = (LinearLayout) findViewById(R.id.fr2);
ln2.setOnTouchListener(swipe);

如何使用onInterceptTouch

您应该创建自己的布局并覆盖布局的 onInterceptTouchEvent(MotionEvent ev) 方法。

例如,我创建了自己的布局来扩展相对布局

       @Override
       public boolean onInterceptTouchEvent(MotionEvent ev) {
         return true; // With this i tell my layout to consume all the touch events from its childs
      }
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
        // Log.d(TAG, String.format("ACTION_DOWN | x:%s y:%s", 
            break;
        case MotionEvent.ACTION_MOVE:
        //Log.d(TAG, String.format("ACTION_MOVE | x:%s y:%s", 
            break;
        case MotionEvent.ACTION_UP:
            break;
        }
        return true;
    }
当我在我的布局

上放置一个按钮时,即使我单击了该按钮,我的布局也会消耗所有 touchEvent,因为onInterceptTouchEvent总是返回 true。

希望这应该对您有所帮助

在布局中添加android:onClick="tapEvent",你想要点击。通过更改MAX_TAP_COUNT值,您可以使用任意数量的点击。

private long thisTime = 0;
private long prevTime = 0;
private int tapCount = 0;
private static  final int MAX_TAP_COUNT = 5;
protected static final long DOUBLE_CLICK_MAX_DELAY = 500;

public void tapEvent(View v){
        if (SystemClock.uptimeMillis() > thisTime) {
            if ((SystemClock.uptimeMillis() - thisTime) > DOUBLE_CLICK_MAX_DELAY * MAX_TAP_COUNT) {
                Log.d(TAG, "touch event " + "resetting tapCount = 0");
                tapCount = 0;
            }
            if (tapCount()) {
               //DO YOUR LOGIC HERE
            }
        }
}
private Boolean tapCount(){
        if (tapCount == 0) {
            thisTime = SystemClock.uptimeMillis();
            tapCount++;
        } else if (tapCount < (MAX_TAP_COUNT-1)) {
            tapCount++;
        } else {
            prevTime = thisTime;
            thisTime = SystemClock.uptimeMillis();
            //just incase system clock reset to zero
            if (thisTime > prevTime) {
                //Check if times are within our max delay
                if ((thisTime - prevTime) <= DOUBLE_CLICK_MAX_DELAY * MAX_TAP_COUNT) {
                    //We have detected a multiple continuous tap!
                    //Once receive multiple tap, reset tap count to zero for consider next tap as new start
                    tapCount = 0;
                    return true;
                } else {
                    //Otherwise Reset tapCount
                    tapCount = 0;
                }
            } else {
                tapCount = 0;
            }
        }
        return false;
}

最新更新