单击任何项​​目后关闭导航抽屉

时间:2016-07-29 07:15:40

标签: android android-fragments android-navigation-drawer

我在我的应用中使用了导航抽屉。当用户单击其任何项目时,它将转到另一个活动,但当用户返回到抽屉页面时,它仍处于打开状态。单击其项目后如何关闭该抽屉。

7 个答案:

答案 0 :(得分:2)

使用closeDrawer()方法关闭抽屉并在抽屉的监听器上开始您的其他活动。

例如。

@Override
public void onDrawerClosed(View drawerView) {
    super.onDrawerClosed(drawerView);

    //Start your activity
}

答案 1 :(得分:2)

DrawerLayout mDrawerLayout= (DrawerLayout) findViewById(R.id.drawer_layout)

closeDrawer(); // called when you want to close

  public void closeDrawer() 
  {
     if (mDrawerLayout.isDrawerOpen(GravityCompat.START))
     {
        mDrawerLayout.closeDrawer(GravityCompat.START);
     }
 }

答案 2 :(得分:1)

在转到其他活动

之前,您可以使用drawerLayout.closeDrawers();关闭NavigationDrawer

答案 3 :(得分:0)

我认为您错过closeDrawer()只需在点击导航项Intent

启动其他方法之前调用此方法
 drawerLayout.closeDrawer(GravityCompat.END);

答案 4 :(得分:0)

 @SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) { 
int id = item.getItemId();
    // Create a new fragment and specify the fragment to show based on nav item clicked
    Fragment fragment = null;
    Class fragmentClass = null;
    if (id == R.id.nav_item1) {
        fragmentClass = home.class;
        // Handle the camera action
    } 
 DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
if(fragmentClass.newInstance() instanceof Fragment) {
            fragment = (Fragment) fragmentClass.newInstance();

            if (fragmentClass.getSimpleName().equals("home")) {

                // Insert the fragment by replacing any existing fragment
                FragmentManager fragmentManager = getSupportFragmentManager();

                fragmentManager.beginTransaction().replace(R.id.home_layout, fragment).commit();
                // Highlight the selected item has been done by NavigationView
                item.setChecked(true);
                // Set action bar title
                setTitle(item.getTitle());
                // Close the navigation drawer
                drawer.closeDrawers();
            }
        }

答案 5 :(得分:0)

只需在closeDrawer()内添加onNavigationItemSelected()即可在选择导航抽屉上的任何项目时关闭抽屉。

@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    int id = item.getItemId();

    //write your if logic here

    drawer.closeDrawer(GravityCompat.START,true);
    return false;
}

答案 6 :(得分:-1)

导航视图可能不在前面。尝试通过mNavigationView.bringToFront();将其显示在前面。