首先在onCreate方法中获取菜单项:
//Get menuItem index 0 if (savedInstanceState == null) { MenuItem item = navigationView.getMenu().getItem(0); onNavigationItemSelected(item); }
并在onNavigationItemSelected:
@Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); Fragment fragment = null; switch (id) { case R.id.nav_capture_credentials: fragment = new TestFragment(); break; case R.id.nav_pending_credentials: fragment = new TestOtehrFragment(); break; case R.id.nav_close_session: //Logout break; } if (fragment != null) { FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction() .replace(R.id.container, fragment).commit(); //Set menuItem checked and title item.setChecked(true); setTitle(item.getTitle()); //close navigation view DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); } else { Log.e(TAG, "Error to create a fragment"); } return false; }