2

我希望有一个覆盖视图来接收手势事件,但仍然继续接收父(下)视图的 onTouch 事件。但是,子视图中的手势似乎隐藏了父 onTouch 事件。

布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent">
    <ParentView

            android:background="#FFFFFF"
            android:orientation="horizontal"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent">

        <ChildView android:background="#FF4433"
                   android:orientation="horizontal"
                   android:layout_width="fill_parent"
                   android:layout_height="200dp" android:layout_marginTop="100dp">

        </ChildView>

    </ParentView>
</LinearLayout>

父视图:

public class ParentView extends FrameLayout implements View.OnTouchListener {
    public ParentView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setOnTouchListener(this);
    }

    @Override
    public boolean onTouch(View view, MotionEvent event) {
        Logger.write("Parent is touching");
        return false;  
    }
}

客户端视图:

public class ChildView extends FrameLayout implements View.OnTouchListener {
    private GestureDetector myGestureDetector;
    private boolean isTapping;

    public ChildView(Context context, AttributeSet attrs) {
        super(context, attrs);
        myGestureDetector=new  GestureDetector(context, new MyGestureDetector());
        setOnTouchListener(this);
    }


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

    class MyGestureDetector extends GestureDetector.SimpleOnGestureListener {

        @Override
        public boolean onDown(MotionEvent e) {
            return true;    
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            try {
                final ViewConfiguration vc = ViewConfiguration.get(getContext());
                final int swipeMinDistance = vc.getScaledPagingTouchSlop();
                final int swipeMaxOffPath = vc.getScaledTouchSlop();
                final int swipeThresholdVelocity = vc.getScaledMinimumFlingVelocity() / 2;
                if (Math.abs(e1.getY() - e2.getY()) > swipeMaxOffPath) {
                    return false;
                }

                // right to left swipe
                if (e2.getX() - e1.getX() > swipeMinDistance && Math.abs(velocityX) >
                        swipeThresholdVelocity) {
                    Logger.write("Swipe!!!!!!!!!!!!!!!!!!!!!!!");

                }
            } catch (Exception e) {
                // nothing
            }

            return false;
        }
    }
}
4

1 回答 1

3

在父视图中而不是在子视图中实现 GestureDetector,否则如果父视图有 n 个子视图,则需要 n 个检测器。

于 2013-06-09T14:57:08.840 回答