Search code examples
androidandroid-fragmentsnavigation-drawerandroiddesignsupport

Android switch Fragments in the new design support navigation drawer


how can I switch Fragments in the new design support navigation drawer? I found example codes on the Cheesesquare Github on how to switch fragments using the TabLayout, but not the navigation drawer. Is that the same? I also would not like to recreate fragments when switching, but rather do it like the TabLayout where it retains the fragments instance and the fragment`s content is how the user left it.


Solution

  • Write some code like this:

    navigationView.setNavigationItemSelectedListener(
            new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(MenuItem menuItem) {
            menuItem.setChecked(true);
            mDrawerLayout.closeDrawers();
            switch (menuItem.getItemId()) {
                case R.id.your_menu_id: 
                    getSupportFragmentManager().beginTransaction().replace(R.id.fragment, getFragment(), "SET_A_TAG").addToBackStack("SET_A_TAG").commit();
                    break;
            }
            return true;
        }
    });
    
    private YourFragment getFragment() {
        YourFragment f = getSupportFragmentManager().findFragmentByTag("SET_A_TAG");
        if (f == null) {
            f = new YourFragment();
        }
        return f;
    }