How to close Drawer layout on BackPress in Android?

前端 未结 4 749
无人共我
无人共我 2020-12-03 08:09

I press the navigation drawer, then if I press back button, the app exits rather than returning to the previous activity. If I change the xml file, then this problem doesn\'

相关标签:
4条回答
  • 2020-12-03 08:51

    @Hiren Patel's answer is the most elegant so far, but you should set:

    mDrawerLayout.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
    

    Or

    mDrawerLayout.descendantFocusability = ViewGroup.FOCUS_BEFORE_DESCENDANTS
    

    Just so you don't block the other child views from receiving focus, and thus blocking the soft keyboard for instance.

    0 讨论(0)
  • 2020-12-03 08:52

    I have done this way:

    private DrawerLayout mDrawerLayout;
    

    onCreate():

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);  
    mDrawerLayout.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
    

    Hope this will help you.

    0 讨论(0)
  • 2020-12-03 08:57
    ListView mDrawerList;
    
    @Override
    public void onBackPressed() {
    // TODO Auto-generated method stub
    
    if(mDrawerLayout.isDrawerOpen(mDrawerList)){
        mDrawerLayout.closeDrawer(mDrawerList);
    }else{
        super.onBackPressed();
    }
    }
    
    0 讨论(0)
  • 2020-12-03 09:03

    This will close the drawer when it's open and back is pressed rather than taking you back to the previous activity (or exiting).

    DrawerLayout drawer...
    
    @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
    
        if(drawer.isDrawerOpen(Gravity.LEFT)){
            drawer.closeDrawer(Gravity.LEFT);
        }else{
            super.onBackPressed();
        }
    }
    
    0 讨论(0)
提交回复
热议问题