Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Navigate without creating a new instance of Fragment - Navigation Component

Is it possible to use navigate function from Android Navigation Component without creating a new instance of fragment but as restoring the previous one?

I tried to restore the previous fragment but only with the use of the navigate function data can be transferred between the fragments.

like image 871
Patryk Kubiak Avatar asked Nov 16 '18 14:11

Patryk Kubiak


1 Answers

Not yet but i guess they are working on it. New instance is always being created for now. But if you write your own navigator, it's possible.

@Navigator.Name("keep_state_fragment") // `keep_state_fragment` is used in navigation xml
class KeepStateNavigator(
    private val context: Context,
    private val manager: FragmentManager, // Should pass childFragmentManager.
    private val containerId: Int
) : FragmentNavigator(context, manager, containerId) {

    override fun navigate(
        destination: Destination,
        args: Bundle?,
        navOptions: NavOptions?,
        navigatorExtras: Navigator.Extras?
    ): NavDestination? {
        val tag = destination.id.toString()
        val transaction = manager.beginTransaction()

        var initialNavigate = false
        val currentFragment = manager.primaryNavigationFragment
        if (currentFragment != null) {
            transaction.detach(currentFragment)
        } else {
            initialNavigate = true
        }

        var fragment = manager.findFragmentByTag(tag)
        if (fragment == null) {
            val className = destination.className
            fragment = manager.fragmentFactory.instantiate(context.classLoader, className)
            transaction.add(containerId, fragment, tag)
        } else {
            transaction.attach(fragment)
        }

        transaction.setPrimaryNavigationFragment(fragment)
        transaction.setReorderingAllowed(true)
        transaction.commitNow()

        return if (initialNavigate) {
            destination
        } else {
            null
        }
    }
}

Then you must call like below

val navigator = KeepStateNavigator(this, navHostFragment.childFragmentManager, R.id.nav_host_fragment)
        navController.navigatorProvider.addProvider(navigator)

This is the sample: Github

like image 87
Umut ADALI Avatar answered Nov 01 '22 02:11

Umut ADALI