Jintin
Jintin

Reputation: 1478

Why Fragment have non-empty constructor now?

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;
}

Upvotes: 1

Views: 378

Answers (1)

Jintin
Jintin

Reputation: 1478

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.

Upvotes: 2

Related Questions