4

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

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

我如何使用onInterceptTouch

4

2 回答 2

10

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

例如,我创建了自己的布局,它扩展了 RelativeLayout

       @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。

希望这可以帮助你

于 2012-05-05T15:09:53.733 回答
0

在您想要点击的布局中添加 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;

}
于 2017-03-20T05:23:19.637 回答