1

We've been told not pass variable via Fragment constructor for a long time. But it seems Fragment itself now have other Fragment constructor to pass data like below. Is it still best practice for us to not passing data from Fragment constructor? Or is there any trick to get rid of it but only in Framework level?

public Fragment() {
    initLifecycle();
}

@ContentView
public Fragment(@LayoutRes int contentLayoutId) {
    this();
    mContentLayoutId = contentLayoutId;
}
Jintin
  • 1,426
  • 13
  • 22
  • Does this answer your question? [why fragment have default constructor?](https://stackoverflow.com/questions/42174775/why-fragment-have-default-constructor) – David Ibrahim Dec 25 '20 at 04:07
  • 1
    Slightly different, I'm wondering why Android provide this new constructor but suggest us not to, but I found the FragmentFactory which can help us fix the issue now. Thanks @DavidIbrahim – Jintin Dec 25 '20 at 04:14

1 Answers1

2

Found the answer, according to Android documentation.

You must set a custom FragmentFactory if you want to use a non-default constructor to ensure that your constructor is called when the fragment is re-instantiated. https://developer.android.com/reference/androidx/fragment/app/Fragment#Fragment(int)

So we have this new constructor can be used, but we still have to provide FragmentFactory to deal with the case fragment is recreated.

Jintin
  • 1,426
  • 13
  • 22