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?