android 多点触控_实现

最近研究安卓手机手柄,略有成绩,总结一下多点触控的实现。

android支持多点触控,但是这些信息直接加载在各种touch_action里,没有比较上层的封装,所以需要人为主动的去区别分发。

当一个touch事件产生以后,首先发给上层子view处理,如果子view处理并截断down事件,那么就会获得focus,接下来的touch事件都会往这个focus view分发。所以,处理多点触摸,需要统一的touch接收(一般为父view),父view接收到一个touch事件后判断是属于哪一个子view的事件,然后分发,最后子view处理。

对于普通的touch事件(touch_down,touch_up),可以同过geiActionIndex()获取到当前action索引信息(在touch列表里是第几个touch),然后通过getX(i)getY(i)获取当前touch的point坐标,判断point属于哪个子view,然后分发。

 

    public boolean onTouch(View v, MotionEvent event) {

        int index = event.getActionIndex();
        Point point = new Point((int)event.getX(index), (int)event.getY(index));

        if (isPointInTheFrame(point, aFrame)) {
            aTextViewOnTouch(event);
        }
        else if (isPointInTheFrame(point, bFrame)) {
            bTextViewOnTouch(event);
        }
        else if (isPointInTheFrame(point, cFrame)) {
            cTextViewOnTouch(event);
        }

        return true;
    }

 

    /**
     * aTextView touch处理
     */
    public void aTextViewOnTouch(MotionEvent event) {
                 //屏蔽action索引信息
         int action = event.getActionMasked()%5;
         if (action == MotionEvent.ACTION_DOWN) {
         }
         else if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
         }
    }

 

对于touch_move事件,自带索引信息是属于第一个touch的索引信息,无法获取到实际move的touch的index,这时候就要遍历pointers,把属于某个view的pointer信息发给该子view,子view根据pointer左边处理move事件。

/**
     * 监听touch事件,分发,多点触控相关
     */
    @Override
    public boolean onTouch(View v, MotionEvent event) {    
        int index = event.getActionIndex();
        Point point = new Point((int)event.getX(index), (int)event.getY(index));
        int action = event.getActionMasked()%5;
        if (action == MotionEvent.ACTION_MOVE) {
            int count = event.getPointerCount();
            for (int i = 0; i < count; i++) {
                point = new Point((int)event.getX(i), (int)event.getY(i));
                if (isPointInTheFrame(point, rockerFrame)) {
                    rockerView.touch(action, point);            
                }
                else {
                }
            }
        }
        else {
            if (isPointInTheFrame(point, aFrame)) {
                aTextViewOnTouch(event);
            }
            else if (isPointInTheFrame(point, bFrame)) {
                bTextViewOnTouch(event);
            }
            else if (isPointInTheFrame(point, cFrame)) {
                cTextViewOnTouch(event);
            }
            else if (isPointInTheFrame(point, dFrame)) {
                dTextViewOnTouch(event);
            }
        }

        return true;
    }
                

到此,基本多点触控的问题就差不多了。

当然,简单的界面,不妨试一试splitMotionEvents,呵呵。

posted on 2013-06-05 18:01  asi24  阅读(543)  评论(0编辑  收藏  举报