Android Jetpack Navigation with ViewPager and TabLayout

前端 未结 5 812
面向向阳花
面向向阳花 2020-12-13 10:09

For a new app i use Jetpack Navigation Library to implement proper back navigation. The first level of navigation is a navigation drawer which works fine with jetpack naviga

5条回答
  •  佛祖请我去吃肉
    2020-12-13 10:39

    Yes, but you will have to implement your own custom destination, by implementing the class Navigator and overriding at least the methods popBackStack() and navigate().

    In your navigate, you will have to call the ViewPager.setCurrentTab() and add it to your back stack. Something like:

    lateinit var viewPager: ViewPager? = null // you have to provide this in the constructor
    
    private val backstack: Deque> = ArrayDeque
    
    override fun navigate(destination: Destination, args: Bundle?,
                          navOptions: NavOptions?, navigatorExtras: Extras?
    ): NavDestination? {
    
        viewPager.currentItem = destination.id
        backstack.remove(destination.id) // remove so the stack has never two of the same
        backstack.addLast(destination.id)
    
        return destination
    }
    

    In your popBackStack, you will have to set back the last item selected. Something like:

    override fun popBackStack(): Boolean {
        if(backstack.size() <= 1) return false
    
        viewPager.currentItem = backstack.peekLast()
        backstack.removeLast()
    
        return true
    }
    

    You can find a brief explanation on Android docs and this example of custom navigator for FragmentDialog.

    After implementing your ViewPagerNavigator, you will have to add it to your NavController and set the listeners of tab views selection to call NavController.navigate().

    I hope someone will implement a library for all this common patterns (ViewPager, ViewGroup, FragmentDialog), if anyone find it, put it on the comments.

提交回复
热议问题