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

前端 未结 13 2030
误落风尘
误落风尘 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:23

    You don't really need a ViewPager to work with BottomNavigation and the new Navigation architecture component. I have been working in a sample app that uses exactly the two, see here.

    The basic concept is this, you have the main activity that will host the BottomNavigationView and that is the Navigation host for your navigation graph, this is how the xml for it look like:

    activity_main.xml

    
    
    
        
    
        
    
    
    

    The navigation Menu (tabs menu) for the BottomNavigationView looks like this:

    navigation.xml

    
    
    
        
    
        
    
        
    
        
    
        
    
    
    

    All of this is just the BottomNavigationView setup. Now to make it work with the Navigation Arch Component you need to go into the navigation graph editor, add all your fragment destinations (in my case I have 5 of them, one for each tab) and set the id of the destination with the same name as the one in the navigation.xml file:

    This will tell android to make a link between the tab and the fragment, now every time the user clicks the "Home" tab android will take care of loading up the correct fragment. There is also one piece of kotlin code that needs to be added to your NavHost (the main activity) to wire things up with the BottomNavigationView:

    You need to add in your onCreate:

    bottomNavigation.setupWithNavController(Navigation.findNavController(this, R.id.my_nav_host_fragment))
    

    This tells android to do the wiring between the Navigation architecture component and the BottomNavigationView. See more in the docs.

    To get the same beahvior you have when you use youtube, just add this:

    navigation.setOnNavigationItemSelectedListener {item ->
    
                onNavDestinationSelected(item, Navigation.findNavController(this, R.id.my_nav_host_fragment))
    
            }
    

    This will make destinations go into the backstack so when you hit the back button, the last visited destination will be popped up.

提交回复
热议问题