I need to use an android navigation drawer with a different fragment for each navigation item, but my problem is:
*How to keep the instances of the fragments and reuse them when the navigation item is touched.
*I don't want have to start a fragment already instantiated again, again and again, it takes to much time of the user.
can anyone help me?
here is a piece of my code:
public void selectDrawerItem(MenuItem menuItem) {
// Create a new fragment and specify the fragment to show based on nav item clicked
Fragment fragment = null;
Class fragmentClass;
switch(menuItem.getItemId()) {
case R.id.nav_inicio:
fragmentClass = DestaquesFragment.class;
break;
case R.id.nav_cardapio:
fragmentClass = CategoriasFragment.class;
break;
case R.id.nav_meusPedidos:
fragmentClass = MeusPedidosFragment.class;
break;
default:
fragmentClass = DestaquesFragment.class;
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.contentCompartilhado, fragment).commit();
// Highlight the selected item has been done by NavigationView
menuItem.setChecked(true);
// Set action bar title
setTitle(menuItem.getTitle());
// Close the navigation drawer
drawer.closeDrawers();
}