如何调度触摸事件给孩子食用后 [英] How to dispatch touch events to children after consuming

查看:134
本文介绍了如何调度触摸事件给孩子食用后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

的布局是这样的:

查看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);

这篇关于如何调度触摸事件给孩子食用后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆