Question

I have two fragments.

In first fragment I have a container static (LinearLayout) that to the view of fragment. In this container i do a inflation of several views.

I change to a second fragment, but when i return to the first fragment the views inflated disappeared.

How I can save the state of the container? Someone can give me a example? Thanks for yout help and attention

enter image description here

Était-ce utile?

La solution

onCreateView is being called again upon returning and your fragment is being recreated. One solution is to save your fragment state in onSaveInstanceState and reload it in onCreateView:

public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    ..
    if (savedInstanceState != null) {
       // reload state
    }
    ..
}

public void onSaveInstanceState (Bundle outState) {
    // save dynamic state in outState
}

EDIT:

I've found this to work if you would like to keep the actual view:

private View mLayout;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {

    if (mLayout == null) {
      // this is the first time onCreateView has been called
      mLayout = inflater.inflate(..);
    } else {
      // remove previous parent
      ViewParent parent = mLayout.getParent();
      if (parent != null)
        ((ViewGroup) parent).removeView(mLayout);
    }
    return mLayout;
}

Autres conseils

The problem is with the saveinstance. The fragment save the state of the views that belongs to the fragment, but the other view that result of the inflations disappear.

I don't know how save the state (when change of fragment) inside a container, that change several times (dinamic)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top