2013-05-01 60 views
0

我在我的活动中有一个按钮网格。当用户通过这个按钮网格滑动他们的手指时,我希望触摸的所有按钮基本上都被记录下来,这样我就知道哪些按钮被触摸了。OnTouchListener MotionEvent.ACTION_MOVE:只获取第一个视图

我一直在做这方面的研究,我没有看到如何做到这一点,因为大多数例子是与位图。它选择的第一个视图是唯一从我的OnTouchListener中挑选的视图。从我的读数中,MotionEvent.ACTION_MOVE是什么被用于这个,我看到有人说,使用view.getRawX()view.getRawY(),但我不明白这将用于确定哪些其他按钮被按下,哪些不是当用户是在屏幕上滑动手指。

我是Android新手,所以如果这是比我想象的更简单的任务,我很抱歉。任何意见都会非常感谢,因为我不认为这应该如此复杂。感谢您的时间! :)

回答

1

一旦视图返回肯定地说,它消耗的触摸事件,意见其余部分将不接收它。你可以做的是让一个自定义ViewGroup(你说你有一个网格,我只是假设GridView?),其截取和处理所有触摸事件:

public class InterceptingGridView extends GridView { 
    private Rect mHitRect = new Rect(); 

    public InterceptingGridView (Context context) { 
     super(context); 
    } 

    public InterceptingGridView (Context context, AttributeSet attrs) { 
     super(context, attrs); 
    } 

    @Override 
    public boolean onInterceptTouchEvent (MotionEvent ev) { 
     //Always let the ViewGroup handle the event 
     return true; 
    } 

    @Override 
    public boolean onTouchEvent (MotionEvent ev) { 
     int x = Math.round(ev.getX()); 
     int y = Math.round(ev.getY()); 

     for (int i = 0; i < getChildCount(); i++) { 
      View child = getChildAt(i); 
      child.getHitRect(mHitRect); 

      if (mHitRect.contains(x, y)) { 
       /* 
       * Dispatch the event to the containing child. Note that using this 
       * method, children are not guaranteed to receive ACTION_UP, ACTION_CANCEL, 
       * or ACTION_DOWN events and should handle the case where only an ACTION_MOVE is received. 
       */ 
       child.dispatchTouchEvent(ev); 
      } 
     } 

     //Make sure to still call through to the superclass, so that 
     //the ViewGroup still functions normally (e.g. scrolling) 
     return super.onTouchEvent(ev); 
    } 
} 

你选择如何处理该事件依赖于你需要的逻辑,但是外包是让容器视图消耗所有触摸事件,并让它处理将事件分派给子项。

+0

我不完全确定这是做什么,因为大多数术语我以前没有见过。我是Android和Java的新手(之前只使用过C++),我的歉意! – Dani 2013-05-01 17:01:29

+0

看看[这个链接](http://developer.android.com/training/gestures/viewgroup.html) – kcoppock 2013-05-01 17:07:49

+0

哦,男孩,这需要一段时间才能搞清楚。谢谢你! – Dani 2013-05-01 19:48:20

0

也许这将帮助你:

@Override 
public boolean onTouch(View v, MotionEvent event) { 

     int action = event.getAction() & MotionEvent.ACTION_MASK; 
     int pointerIndex = (event.getAction() & MotionEvent.ACTION_POINTER_ID_MASK) >> MotionEvent.ACTION_POINTER_ID_SHIFT; 
     int pointerId = event.getPointerId(pointerIndex); 


     switch (action) { 
     case MotionEvent.ACTION_DOWN: 
     case MotionEvent.ACTION_POINTER_DOWN: 

      break; 

     case MotionEvent.ACTION_UP: 
     case MotionEvent.ACTION_POINTER_UP: 
     case MotionEvent.ACTION_CANCEL: 

      break; 

     case MotionEvent.ACTION_MOVE: 
      int pointerCount = event.getPointerCount(); 
      for (int i = 0; i < pointerCount; i++) { 

      } 
      break; 
     } 

     return true; 

} 

它适用于多点触控

相关问题