我的代码完美运行:每次单击导航抽屉中的项目时,都会选择该项目。
当然,我想使用默认片段(主页)启动应用程序,但 Navigation Drawer 没有选择该项目。如何以编程方式选择该项目?
public class BaseApp extends AppCompatActivity { //Defining Variables protected String LOGTAG = "LOGDEBUG"; protected Toolbar toolbar; protected NavigationView navigationView; protected DrawerLayout drawerLayout; private DateManager db = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.base_layout); navigationView = (NavigationView) findViewById(R.id.navigation_view); // set the home/dashboard at startup FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); fragmentTransaction.replace(R.id.frame, new DashboardFragment()); fragmentTransaction.commit(); setNavDrawer(); } private void setNavDrawer(){ // Initializing Toolbar and setting it as the actionbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); //Initializing NavigationView //Setting Navigation View Item Selected Listener to handle the item click of the navigation menu navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() { // This method will trigger on item Click of navigation menu @Override public boolean onNavigationItemSelected(MenuItem menuItem) { //Checking if the item is in checked state or not, if not make it in checked state // I THINK THAT I NEED EDIT HERE... if (menuItem.isChecked()) menuItem.setChecked(false); else menuItem.setChecked(true); //Closing drawer on item click drawerLayout.closeDrawers(); //Check to see which item was being clicked and perform appropriate action switch (menuItem.getItemId()) { //Replacing the main content with ContentFragment case R.id.home: DashboardFragment dashboardFragment = new DashboardFragment(); FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); fragmentTransaction.replace(R.id.frame, dashboardFragment,"DASHBOARD_FRAGMENT"); fragmentTransaction.commit(); return true; [...]
我认为我需要在这里编辑:
if (menuItem.isChecked()) menuItem.setChecked(false); else menuItem.setChecked(true);
或者在onCreateApp 启动时使用 FragmentTransaction。
onCreate
谢谢您的支持。
使用下面的代码:
navigationView.getMenu().getItem(0).setChecked(true);
调用后调用此方法setNavDrawer();
setNavDrawer();
该getItem(int index)方法获取MenuItem然后您可以调用setChecked(true);on that MenuItem,您所要做的就是找出默认具有的元素索引,并将 0 替换为该索引。
getItem(int index)
MenuItem
setChecked(true);
您可以通过调用选择(突出显示)该项目
onNavigationItemSelected(navigationView.getMenu().getItem(0));
编辑 在 nexus 4 上不起作用,支持库修订版 24.0.0。我推荐使用
navigationView.setCheckedItem(R.id.nav_item);