如何处理在子视图中单击,并在父ViewGroups中触摸?

and*_*vil 6 android ontouchlistener viewgroup

在我的布局中,我有一个像这样的结构:

--RelativeLayout
  |
  --FrameLayout
    |
    --Button, EditText...
Run Code Online (Sandbox Code Playgroud)

我想在RelativeLayout和FrameLayout中处理触摸事件,所以我在这两个视图组中设置了onTouchListener.但只捕获RelativeLayout中的触摸.

为了尝试解决这个问题,我编写了自己的CustomRelativeLayout,并覆盖了onInterceptTouchEvent,现在捕获了子ViewGroup(FrameLayout)中的点击,但按钮和其他视图中的单击没有任何效果.

在我自己的自定义布局中,我有这个:

public boolean onInterceptTouchEvent(MotionEvent ev) {
    return true;
}
Run Code Online (Sandbox Code Playgroud)

Yve*_*omb 7

您需要覆盖onInterceptTouchEvent() 每个子onTouchEvent节点,否则它将保留为父节点.

截取ViewGroup中的触摸事件

@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
    /*
    * This method JUST determines whether we want to intercept the motion.
    * If we return true, onTouchEvent will be called and we do the actual
    * scrolling there.
    */
...
    // In general, we don't want to intercept touch events. They should be 
    // handled by the child view.
    return false;
}
Run Code Online (Sandbox Code Playgroud)

您需要返回false以让子处理它,否则您将其返回给父级.

  • 假设我只想为处理某些孩子而覆盖touch事件,那么在此函数内要如何使其起作用?我的意思是,对于某些孩子,它将照常工作,对于某些孩子,父视图将决定他们是否将获得触摸事件。 (2认同)