Android Jetpack Navigation, BottomNavigationView with Youtube or Instagram like proper back navigation (fragment back stack)?

前端 未结 13 2027
误落风尘
误落风尘 2020-12-12 10:25

Android Jetpack Navigation, BottomNavigationView with auto fragment back stack on back button click?

What I wanted, after choosing multiple tabs one after another by

13条回答
  •  情深已故
    2020-12-12 11:11

    I have made an app like this (still not published on PlayStore) that has the same navigation, maybe its implementation is different from what Google does in their apps, but the functionality is the same.

    the structure involves I have Main Activity that I switch the content of it by showing/hiding fragments using:

    public void switchTo(final Fragment fragment, final String tag /*Each fragment should have a different Tag*/) {
    
    // We compare if the current stack is the current fragment we try to show
    if (fragment == getSupportFragmentManager().getPrimaryNavigationFragment()) {
      return;
    }
    
    // We need to hide the current showing fragment (primary fragment)
    final Fragment currentShowingFragment = getSupportFragmentManager().getPrimaryNavigationFragment();
    
    final FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
    if (currentShowingFragment != null) {
      fragmentTransaction.hide(currentShowingFragment);
    }
    
    // We try to find that fragment if it was already added before
    final Fragment alreadyAddedFragment = getSupportFragmentManager().findFragmentByTag(tag);
    if (alreadyAddedFragment != null) {
      // Since its already added before we just set it as primary navigation and show it again
      fragmentTransaction.setPrimaryNavigationFragment(alreadyAddedFragment);
      fragmentTransaction.show(alreadyAddedFragment);
    } else {
      // We add the new fragment and then show it
      fragmentTransaction.add(containerId, fragment, tag);
      fragmentTransaction.show(fragment);
      // We set it as the primary navigation to support back stack and back navigation
      fragmentTransaction.setPrimaryNavigationFragment(fragment);
    }
    
    fragmentTransaction.commit();
    }
    

提交回复
热议问题