M
M
mitaichik2020-07-22 19:27:06
Android
mitaichik, 2020-07-22 19:27:06

How to correctly restore a fragment in a fragment?

Good afternoon.
I have not yet encountered the work of a fragment in a fragment, tell me how to restore their state correctly?

There is an activity Activity
FragmentA is installed in it.
FragmentA is set to FragmentB.

In code it looks like this:

// активити
public void onCreate(Bundle savedInstanceState)
{
  super.onCreate(R.layout.activity, savedInstanceState);
  Fragment fragment = FragmentA.newInstance(....);
  setFragment(R.id.container, fragment); // установка с помощью FragmentManager
}

// FragmentA

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
  {
    View layout = createView(R.layout.fragment_a, inflater);
    Fragment fragment = FragmentB.newInstance(...);
    setFragment(R.id.container_sub, fragment);
    return layout;
  }

// в FragmentB ничего какого-то интересного кода нет


The problem is that when the activity is recreated, fragments are recreated (the state is lost), but it is necessary that they be restored.

With the output activated, wrap the creation of the fragment in a check for savedInstanceState:

// активити
public void onCreate(Bundle savedInstanceState)
{
  super.onCreate(R.layout.activity, savedInstanceState);

  if (savedInstanceState == null) {
    Fragment fragment = FragmentA.newInstance(....);
    setFragment(R.id.container, fragment); 
  }
}


Is it correct to restore a fragment in a fragment to do the same, that is, in FragmentA to do something like

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
  View layout = createView(R.layout.fragment_a, inflater);
  if (savedInstanceState == null) {
    Fragment fragment = FragmentB.newInstance(...);
    setFragment(R.id.container_sub, fragment);
  }
  return layout;
}


At first glance, it seems to work as it should, but is it right to do so?
Can you suggest a good article or a book that describes in detail how all these fragments and the FragmentManager work - everywhere I have seen it is described somehow superficially ....

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2020-07-23
@mitaichik

It's not very clear what the setFragment method is. For this code to work correctly inside a fragment, getChildFragmentManager must be used. Then everything will be ok.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question