Android Navigation Drawer Doesn't Pass onTouchEvent to Activity

后端 未结 5 1067
忘掉有多难
忘掉有多难 2021-01-02 04:57

I have an Activity which uses the Android NavigationDrawer. When using only fragments (as usual), everything works perfect. But now I

5条回答
  •  星月不相逢
    2021-01-02 05:30

    While working on the same problem I was inspired by guy_m's answer and boiled down his proposals to the following solution.

    Again it amounts to extending DrawerLayout and overriding onInterceptTouchEvent(). The logic is simple:

    • Whenever the touch event occurs off the drawer view (the slideable part), we return false. Then our DrawerLayout is out of the game when it comes to handling the event -- the event is handled by whatever view we put into the DrawerLayout at the respective position.

    • On the other hand, when the event occurs inside the drawer view, we delegate to super.onInterceptTouchEvent() to decide what to do with the event. That way the drawer will slide in and out as before on touch gestures happening on itself.

    The following code sample is for a DrawerLayout whose drawer view is located on the right (android:gravity="right"). It should be obvious how to modify it to cover also the case of a left-placed drawer.

    public class CustomDrawerLayout extends DrawerLayout
    {
      @Override
      public boolean onInterceptTouchEvent( MotionEvent event )
      {
        final View drawerView = getChildAt( 1 );
        final ViewConfiguration config = ViewConfiguration.get( getContext() );
        // Calculate the area on the right border of the screen on which
        // the DrawerLayout should *always* intercept touch events.
        // In case the drawer is closed, we still want the DrawerLayout
        // to respond to touch/drag gestures there and reopen the drawer!
        final int rightBoundary = getWidth() - 2 * config.getScaledTouchSlop();
    
        // If the drawer is opened and the event happened
        // on its surface, or if the event happened on the
        // right border of the layout, then we let DrawerLayout
        // decide if it wants to intercept (and properly handle)
        // the event.
        // Otherwise we disallow DrawerLayout to intercept (return false),
        // thereby letting its child views handle the event.
        return ( isDrawerOpen( drawerView ) && drawerView.getLeft() <= event.getX()
                || rightBoundary <= event.getX() )
                && super.onInterceptTouchEvent( event );
      }
    }
    

提交回复
热议问题