Save the instance of a Fragment

Asked

Viewed 416 times

0

To MainActivity calls Fragment upon being started.

I have tabs that alternate through Fragments. I trace a route in one of the Fragments and when leaving, clicking on the tab and when returning, the route disappears, I would like it to be instantiated yet.

I would like, for a Bundle perhaps, that when returning from another tab, I can continue with the route drawn on the screen.

If anyone can help me in this matter. Save the Fragment state?

I tried to implement something like in the answer above but it did not work.

  • How you’re doing the TAB toggle?

1 answer

1


Look, you can use the very life cycle of fragment like the onActivityCreated. Usually this kind of situation of losing data and having to recover happens, for example, when the screen is rotated. In this case, to record a route, you basically need a array coordinate right?! So come on, see the code below and adapt it to your needs:

public class ExampleFragment extends Fragment {
    private List<String> myData;

    @Override
    public void onSaveInstanceState(final Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putSerializable("list", (Serializable) myData);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (savedInstanceState != null) {
            myData = (List<String>) savedInstanceState.getSerializable("list");
        } else {
            if (myData != null) {

            } else {

                myData = computeData();
            }
        }
    }
}

From one observed in these gifs regarding the moment he saves and the moment of restoration of one Fragment:

Saving and Restoring State

inserir a descrição da imagem aqui

I found this article and found it very interesting. Worth reading.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.