How to change the fragment in the onNewIntent method, if everything happens here:

@SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); Fragment fragment = null; Class fragmentClass = null; if(fragmentClass == null) { fragmentClass = HelloFragment.class; } if (id == R.id.nav_camera) { fragmentClass = ExamFragment.class; } else if (id == R.id.nav_gallery) { fragmentClass = ResultsFragment.class; } else if (id == R.id.nav_slideshow) { fragmentClass = RemindersFragment.class; } else if (id == R.id.nav_share) { } if(fragment == null) { try { fragment = (Fragment) fragmentClass.newInstance(); } catch (Exception e) { e.printStackTrace(); } } // Вставляем фрагмент, заменяя текущий фрагмент FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction().replace(R.id.container,fragment).commit(); // Выделяем выбранный пункт меню в шторке item.setChecked(true); // Выводим выбранный пункт в заголовке setTitle(item.getTitle()); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } 
  • In theory, you can simply call this method by transferring to it a self-created menu object that has been assigned the desired id - YuriySPb

1 answer 1

Two options come to my mind.

  1. In onCreateOptionsMenu, save the menu to some activation field. When required, call onNavigationItemSelected(menu.findItem(какой-нибудь id)); . The problem here is that callback onCreateOptionsMenu will be called later than onCreate , so this cannot be done in onCreate.
  2. Store a set of objects that will describe the menu items. For example, keep this information in classes of fragments. That is, for example, instead of setTitle(item.getTitle()); will be setTitle(fragment.getTitle()); etc..
  3. As Yury noted, you can create your own implementation of the MenuItem interface and pass it to the onNavigationItemSelected method. It will be a cross between the first and second solution.