How reuse fragments already instantiated on Navigation Drawer?

Viewed 698

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();
}
1 Answers

When you replace your fragment set a tag name for it in order to retrieve it later for reusing that.

getFragmentManager().beginTransaction().replace(R.id.fragmentContentPlaceHolder,yourFragment,"yourFragment").addToBackStack("yourFragment").commitAllowingStateLoss();

now we have a fragment in stack with the name of yourFragment

for reusing of that we try to find it by tag name

  YourFragment yourFragment= (YourFragment)getFragmentManager().findFragmentByTag("yourFragment");

all done good luck !

Related