如何调度触摸事件给孩子食用后给孩子、事件

2023-09-06 14:03:44 作者:好记的

的布局是这样的:

查看1是一个自定义布局 FlipperLayout 和View 2是一个扩展的ListView PinnedHeaderListView ,我想添加一个拉刷新功能。查看1需要听,以翻转向左或向右触摸事件。查看2也需要触摸事件。而问题是,如果查看1所消耗的触摸事件,查看2无法得到它。

View 1 is a self-defined layout FlipperLayout, and View 2 is a extended ListView PinnedHeaderListView which I want to add a "pull to refresh" function. View 1 need to listen to touch event in order to flip left or right. View 2 also need the touch event. And problem is that if View 1 consumed the touch event, View 2 can't get it.

如何分派事件查看2连后视图1食用呢?

推荐答案

考虑以下自定义布局:

class FlingLinearLayout extends LinearLayout {

    private GestureDetector mDetector;

    public FlingLinearLayout(Context context) {
        super(context);
        setOrientation(LinearLayout.VERTICAL);
        OnGestureListener listener = new SimpleOnGestureListener() {
            @Override
            public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
                Log.d(TAG, "onFling vx: " + velocityX + ", vy: " + velocityY);
                if (Math.abs(velocityX) > Math.abs(velocityY)) {
                    String text = (velocityX > 0? "left to right" : "right to left") + " fling";
                    Toast.makeText(getContext(), text, Toast.LENGTH_LONG).show();
                    return true;
                }
                return false;
            }
        };
        mDetector = new GestureDetector(context, listener);
        setBackgroundColor(0xaaff0000);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        //Log.d(TAG, "onTouchEvent " + event);
        // handle own events (initiated in red area)
        mDetector.onTouchEvent(event);
        return true;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        //Log.d(TAG, "onInterceptTouchEvent " + ev);
        // handle child events
        // note: if you horizontally fling over button its onClick() is not performed
        return mDetector.onTouchEvent(ev);
    }
}

和它在你的活动用法:

ViewGroup ll = new FlingLinearLayout(this);
Button b;
OnClickListener l = new OnClickListener() {
    @Override
    public void onClick(View v) {
        Button b = (Button) v;
        Log.d(TAG, "onClick " + b.getText());
    }
};
b = new Button(this);
b.setText("first");
b.setOnClickListener(l);
ll.addView(b);
b = new Button(this);
b.setText("second");
b.setOnClickListener(l);
ll.addView(b);
b = new Button(this);
b.setText("third");
b.setOnClickListener(l);
ll.addView(b);
setContentView(ll);