如何select导航抽屉中的第一个项目并在应用程序启动时打开一个片段

我用NavigationView创build了MainActivity 。 当Activity打开时,我想自动select导航抽屉中的第一个项目,并打开该项目下的Fragment 。 我search了很多,但没有find任何适当的解决scheme。

什么是正确的方法来做到这一点?

Main Activity

 public class MainActivity extends AppCompatActivity implements Config { private NavigationView navigationView; private DrawerLayout drawerLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); toolbar.setTitleTextColor(getResources().getColor(R.color.colorIcons)); if (null != getSupportActionBar()) getSupportActionBar().setLogo(R.drawable.ic_blogger_white); //Start PostListFragmentWebView /*PostListFragmentWebView postListFragmentWebView = new PostListFragmentWebView(); getSupportFragmentManager().beginTransaction() .replace(R.id.frame, postListFragmentWebView) .commit();*/ //Initializing NavigationView navigationView = (NavigationView) findViewById(R.id.navigationView); //Setting Navigation View Item Selected Listener to handle the item click of the navigation menu navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(MenuItem menuItem) { //Checking if the item is in checked state or not, if not set it to checked state. if (menuItem.isChecked()) menuItem.setChecked(false); else menuItem.setChecked(true); //Closing drawer on item click drawerLayout.closeDrawers(); //Check to see which item was clicked and perform the appropriate action. switch (menuItem.getItemId()) { case R.id.posts: PostListFragmentWebView postListFragment = new PostListFragmentWebView(); getSupportFragmentManager().beginTransaction() .replace(R.id.frame, postListFragment) .commit(); return true; case R.id.pages: PageListFragmentWebView pagetListFragment = new PageListFragmentWebView(); getSupportFragmentManager().beginTransaction() .replace(R.id.frame, pagetListFragment) .commit(); return true; case R.id.blog: BlogInfoFragmentWebView blogInfoFragment = new BlogInfoFragmentWebView(); getSupportFragmentManager().beginTransaction() .replace(R.id.frame, blogInfoFragment) .commit(); return true; default: Toast.makeText(getApplicationContext(), getResources().getString(R.string.drawer_error), Toast.LENGTH_SHORT).show(); return true; } } }); // Initializing Drawer Layout and ActionBarToggle drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout); ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open_drawer, R.string.close_drawer) { @Override public void onDrawerClosed(View drawerView) { // Code here will be triggered once the drawer closes as we don't want anything to happen so we leave this blank. super.onDrawerClosed(drawerView); } @Override public void onDrawerOpened(View drawerView) { // Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank. super.onDrawerOpened(drawerView); } }; //Setting the actionbarToggle to drawer layout drawerLayout.setDrawerListener(actionBarDrawerToggle); drawerLayout.getChildAt(0).setSelected(true); //calling sync state is necessary or else your hamburger icon wont show up actionBarDrawerToggle.syncState(); } } 

onCreate() ,以下代码将在第一次启动时加载第一个项目的片段:

 if (savedInstanceState == null) { navigationView.getMenu().performIdentifierAction(R.id.posts, 0); } 

感谢calvinfly这个评论 。

android:checked="true"到第一个菜单项。

并手动select一个项目,使用

 getSupportFragmentManager().beginTransaction().replace(R.id.frame, postListFragment).commit(); 

打开片段。

而不是正常的听众…

 navView.setNavigationItemSelected(new Navigation.View.OnNavigationItemSelectedListener() {bla, bla, bla}) 

创build侦听器作为Obj:

 NavigationView.OnNavigationItemSelectedListener navViewListener; navView.setNavigationItemSelectedListener(navViewListener = new NavigationView.OnNavigationItemSelectedListener() {bla, bla, bla}) 

…并使用Obj触发侦听器事件:

 navViewListener.onNavigationItemSelected(navView.getMenu().getItem(0)); 

…其中getItem(0)是第一个菜单项。

在其菜单项XML定义中使用方法getItem(0).setChecked(true)或android:checked =“true”。

设置navigationView.setCheckedItem(R.id.default)后,您还可以使用navigationView.setCheckedItem(R.id.default) ( javadoc )。

只需在onCreate方法中添加下面的代码:

 FragmentTransaction ftrans = getFragmentManager().beginTransaction(); ftrans.replace(R.id.container, <yourfragment>).commit(); 

为我工作!

在考虑方位和其他configuration变化的情况下,可以做得更好。 我们可以select任何导航菜单项取决于我们是否来自以前的状态。 检查:对于导航抽屉挥舞的活动: –

 public static final String SELECTED_NAV_MENU_KEY = "selected_nav_menu_key"; // The selected grid position private int mSelectedNavMenuIndex = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_demo); ........................................................... navigationView.setNavigationItemSelectedListener(this); if (savedInstanceState != null) { // Recover assets mSelectedNavMenuIndex = savedInstanceState.getInt(SELECTED_NAV_MENU_KEY); // Recover menu as selected MenuItem menuItem = navigationView.getMenu().getItem(mSelectedNavMenuIndex); toggleNavMenuItemCheck(menuItem); navigationView.getMenu().performIdentifierAction(menuItem.getItemId(), mSelectedNavMenuIndex); return; } else { MenuItem menuItem = navigationView.getMenu().getItem(mSelectedNavMenuIndex); toggleNavMenuItemCheck(menuItem); navigationView.getMenu().performIdentifierAction(menuItem.getItemId(), mSelectedNavMenuIndex); } } 

帮助取消选中或检查菜单项的切换方法

 private void toggleNavMenuItemCheck(MenuItem menuItem) { if (menuItem.isChecked()){ menuItem.setChecked(false); } else { menuItem.setChecked(true); } } 

这是我如何保存所选菜单项的状态。 检查: –

 @Override public boolean onNavigationItemSelected(MenuItem item) { int id = item.getItemId(); switch (id) { case R.id.nav_explore: showExploreFragment(null); mSelectedNavMenuIndex = 0; break; case R.id.nav_orders: mSelectedNavMenuIndex = 1; break; case R.id.nav_settings: mSelectedNavMenuIndex = 2; break; default: showExploreFragment(null); mSelectedNavMenuIndex = 0; } drawer.closeDrawer(GravityCompat.START); return true; } // Save any important data for recovery @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt(SELECTED_NAV_MENU_KEY, mSelectedNavMenuIndex); } 

注:代码行:

 navigationView.getMenu().performIdentifierAction(menuItem.getItemId(), mSelectedNavMenuIndex); 

可以用代码replace:

 onNavigationItemSelected(menuItem); 

menu.xml记得提及一个项目android:checkableBehavior="single" menu.xml android:checkable="true"android:checkableBehavior="single"

 <item android:id="@+id/pos_item_help" android:checkable="true" android:title="Help" /> <group android:id="@+id/group" android:checkableBehavior="single"> <item android:id="@+id/menu_nav_home" android:icon="@drawable/ic_home_black_24dp" android:title="@string/menu_nav_home" /> </group> 

那么在NavigationItemSelectedListener里面使用setCheckedItem(R.id.item_id_in_menu)来使它被选中。

 @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case R.id.pos_item_pos: navigationView.setCheckedItem(R.id.pos_item_pos); break; case R.id.pos_item_orders: navigationView.setCheckedItem(R.id.pos_item_orders); break; default: } return true; } 

而且,您不必再执行pipe理选定项目的肮脏任务。 navigationView自行pipe理它。

1.)首先着陆到HomeFragment,在MainActivity的onCreate()中使用这个:

 Fragment fragment = new HomeFragment(); // replacing the fragment if (fragment != null) { FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.replace(R.id.content_frame, fragment); ft.commit(); } 

2.)要在navigationDrawer中将项目设置为selected,请将项目设置为在navigation_menu.xml中选中的项目

  android:checked = "true"