How to prevent closing Navigation drawer by touch outside the drawer

后端 未结 3 1694
深忆病人
深忆病人 2020-12-20 19:58

I have an Activity with Navigation Drawer. if user device is table and orientation is landscape - I not need to close drawer by click on item in drawer:

if (         


        
3条回答
  •  醉梦人生
    2020-12-20 20:47

    Simplified version of Noundla's answer which works for me. I wrote my custom Drawer which extends DrawerLayout and implement dispatchTouchEvent() method.

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        if (!this.isDrawerOpen(Gravity.LEFT)) {
            return super.dispatchTouchEvent(event);
        }
        boolean isOutSideClicked = false;
        if (event.getAction() == MotionEvent.ACTION_UP) {
            View content = findViewById(R.id.drawer_view); 
            int[] contentLocation = new int[2];
            content.getLocationOnScreen(contentLocation);
            Rect rect = new Rect(contentLocation[0],
                    contentLocation[1],
                    contentLocation[0] + content.getWidth(),
                    contentLocation[1] + content.getHeight());
            isOutSideClicked = !(rect.contains((int) event.getX(), (int) event.getY()));
        }
        this.setDrawerLockMode(isOutSideClicked ? DrawerLayout.LOCK_MODE_LOCKED_OPEN : DrawerLayout.LOCK_MODE_UNLOCKED);
        return super.dispatchTouchEvent(event);
    }
    

    Also if you want to keep interact with main content fragment while drawer is open you should add this line at the beginning of the method.

    getChildAt(0).dispatchTouchEvent(event);
    

提交回复
热议问题