Skip to content

(Sample 3) Tab Navigation

Kaustubh Patange edited this page Jun 19, 2021 · 7 revisions

The code sets up tab layout navigation in a fragment (the same can be followed for activity).

The snippet covers a very small part of the actual setup. Check the navigation sample for complete example.

class HomeFragment : ValueFragment(R.layout.fragment_home), FragmentNavigator.Transmitter {
    private lateinit var navigator: FragmentNavigator
    private lateinit var tabController: TabNavigationController

    override fun getNavigator(): FragmentNavigator = navigator

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val binding = FragmentHomeBinding.bind(view)
        navigator = FragmentNavigator.with(this, savedInstanceState)
            .initialize(binding.container)

        // Actual tab navigation setup. Rest is handled for you including selection change,
        // animations, many more.
        navigator.install(object: FragmentNavigator.TabNavigation() {
            // The @IdRes of the TabLayout
            override val tabLayoutId: Int = R.id.tabLayout

            // A list of fragments in the order of TabItems (children of TabLayout).
            override val tabNavigationFragments: List<KClass<out Fragment>> = listOf(
                FirstFragment::class,
                SecondFragment::class
            )

            // Slide from left/right animation when selection is changed.
            override val fragmentNavigationTransition: Animation = Animation.SlideHorizontally

            // Retains the view of the fragment so that it will not be destroyed on selecting the different tab.
            override val fragmentViewRetentionType: Navigator.ViewRetention = ViewRetention.RETAIN
        })
    }
}
class FirstFragment : ValueFragment()
class SecondFragment : ValueFragment()