Topmost View因重叠而吞下触摸事件

idi*_*ish 5 java android android-custom-view android-layout android-view

所以这是我的布局结构:

- RelativeLayout (full screen)
  - FrameLayout (full screen)
  - Button (in the middle of the screen)
  - RecyclerView (align parent bottom but with very big padding top to 
    capture the scrolling also in the top of the screen, so it's basically acting like a full screen `RecyclerView`)
Run Code Online (Sandbox Code Playgroud)

所以是的,这些观点相互重叠.

由于RecyclerView它是最顶层的视图,它捕获屏幕上的所有触摸事件,并吞下它们,防止任何触摸"通过它"到它下面的底层视图.(注意:根据基本观点,我不是指RecyclerView孩子而是其他rootview's孩子)

我已经阅读了大量关于传播触摸事件和防止吞咽触摸事件等的stackoverflow帖子,即使看起来非常简单的任务,我也无法实现以下效果:

我想要我RecyclerView捕捉触摸事件,所以它会滚动或其他任何东西.但是我想要rootView认为RecyclerView没有捕获事件,并继续传递给其他孩子(rootview的孩子).

这是我试图做的事情:

1.重写dispatchTouchEventRecyclerView做它的逻辑并返回false作为它没有调度其触摸事件,因此rootview将继续迭代通过其子视图触摸.

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    super.dispatchTouchEvent(ev);
    return false;
}
Run Code Online (Sandbox Code Playgroud)

发生了什么:

RecyclerView功能仍然但是还是吞下所有触摸事件,(只是和以前一样)

2.重写onTouchEventRecyclerView做它的逻辑和返回false.(注意:我知道它似乎不是解决方案,但我试过)

@Override
public boolean onTouchEvent(MotionEvent e) {
    super.onTouchEvent(e);
    return false;
}
Run Code Online (Sandbox Code Playgroud)

发生了什么:

与#1中的结果相同

我已经用同样的想法做了一些调整,但是它们没有那么好用,所以我现在有点无能为力,并希望得到你们的帮助!

azi*_*ian 0

我不确定这个解决方案有多高效/有效/好的解决方案,但这就是我想到的:如果您在根视图中监听触摸事件(RelativeLayout在您的情况下),并将触摸事件分派给所有子视图,该怎么办该布局除了RecyclerView

public class MyRelativeLayout extends RelativeLayout {
    ...

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        final boolean intercept = super.onInterceptTouchEvent(ev);

        // getChildCount() - 1, because `RecyclerView` is the last child
        for (int i = 0, size = getChildCount() - 1; i < size; i++) {
            View v = getChildAt(i);
            v.dispatchTouchEvent(MotionEvent.obtain(ev));
        }

        return intercept;
    }
}
Run Code Online (Sandbox Code Playgroud)

这似乎应该有效。