【问题标题】:Tracing a MotionEvent in a ViewGroup在 ViewGroup 中跟踪 MotionEvent
【发布时间】:2014-04-03 17:06:48
【问题描述】:

我有一个扩展ViewGroup 的类,并希望从中获取每个MotionEvent。到目前为止,我有这个:

class TestViewGroup extends ViewGroup {
     public TestViewGroup(Context context) {
         super(context);
     }

     @Override
     public boolean onTouchEvent(MotionEvent event) {
         Log.d("TestViewGroup", "X: " + (int)event.getX() + " Y: " + (int)event.getY());
         return true;
     }
 }

onTouchEvent(MotionEvent event) 方法能够在我每次将手指放在屏幕上时捕获MotionEvent。但是如果我在手指仍然向下时在屏幕上移动手指,它就不会继续跟踪我手指的坐标。我知道在扩展View 的类中,可以在手指移动通过View 时继续跟踪它。我只是想知道如何将相同的想法应用于ViewGroup

【问题讨论】:

    标签: android view trace touch-event viewgroup


    【解决方案1】:

    我实现了一个非常简单的 ViewGroup 类并复制了您的代码,onTouchEvent 工作正常

    我唯一不同的是实现了所有的构造函数,但一般来说,我也会为 onTochEvent 类调用 super,这似乎没有什么不同。

    所以我想知道您是否遗漏了任何可能产生影响的代码/xml?

    捕捉模拟器和设备上的所有触摸事件,除了构造函数之外,几乎和你的一样。

    public class customViewGroup extends ViewGroup {
    
        public customViewGroup(Context context) {
            super(context,null,0);
       }
    
        public customViewGroup(Context context, AttributeSet attrs) {
            super(context, attrs,0);
    
        }
    
        public customViewGroup(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
        }
    
        @Override
        protected void onLayout(boolean arg0, int arg1, int arg2, int arg3, int arg4) {
    
        }
    
        @Override
        public boolean onTouchEvent(MotionEvent event) {
            Log.d("bThere", "X: " + (int)event.getX() + " Y: " + (int)event.getY());
            return true;//super.onTouchEvent(event);
        }
    
    }
    

    【讨论】:

    • 你知道,你是对的,它与 View 或 ViewGroup 无关,我认为它实际上与我如何集成它有关。我正在尝试将 ViewGroup 放入系统的 WindowManager 中,以便它可以在系统覆盖层上保持持久性(基本上无论顶部有什么活动都显示一个视图)。你知道给 WindowManager 添加一个 View 是否会影响触摸事件传递给它的方式吗?
    • @AeroDroid ... 听起来很有趣,我建议打开另一个问题并重新措辞,同时添加一些代码。您也可以尝试使用 @Override public boolean dispatchTouchEvent(MotionEvent event) {} 作为替代方案,因为它在获取事件方面似乎更强大,但您需要添加一些代码
    • 其实我前段时间刚开了一个新问题,这里请看here
    【解决方案2】:

    您应该添加viewGroup.setClickable(true); 以确保视图可以接收更多的触摸事件。

    【讨论】:

      猜你喜欢
      • 2012-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多