Search code examples
androidandroid-fragmentsfragmentmanagerandroid-fragmentfactory

How to use FragmentFactory with arguments at runtime?


Let's say i have a fragment with constructor that gets an argument at runtime depending on a network request for instance

class MyFragment(private val myArg: Int) : Fragment() {
   // Do layout and other stuff
}

I did a sample FragmentFactory to pass but my question is is there a better way to pass arguments especially when we have various fragments that need arguments in runtime?

class MyFragmentFactory private constructor() : FragmentFactory() {

    var myArg = 0

    override fun instantiate(classLoader: ClassLoader, className: String): Fragment {

        return when (className) {
            MyFragment::class.java.name -> MyFragment(myArg)
            else -> super.instantiate(classLoader, className)
        }
    }
}

There is a method of FragmentManager class

  public final FragmentTransaction replace(@IdRes int containerViewId,
        @NonNull Class<? extends Fragment> fragmentClass, @Nullable Bundle args) {
    return replace(containerViewId, fragmentClass, args, null);
}

how is this method used and can it be used with FragmentFactory, and how are arguments passed to the fragment using this method?


Solution

  • Unfortunately, you cannot pass dynamic arguments to FragmentManager at runtime.
    You still need to use bundle and arguments for the same.

    For more details on this issue, you can track it here and check google's response to it.

    A brief blog about it can be found here