Retaining Fragments

suggest change

In many cases, we can avoid problems when an Activity is re-created by simply using fragments. If your views and state are within a fragment, we can easily have the fragment be retained when the activity is re-created:

public class RetainedFragment extends Fragment {
    // data object we want to retain
    private MyDataObject data;

    // this method is only called once for this fragment
    public void onCreate(Bundle savedInstanceState) {
        // retain this fragment when activity is re-initialized

    public void setData(MyDataObject data) { = data;

    public MyDataObject getData() {
        return data;

This approach keeps the fragment from being destroyed during the activity lifecycle. They are instead retained inside the Fragment Manager. See the Android official docs for more information.

Now you can check to see if the fragment already exists by tag before creating one and the fragment will retain it’s state across configuration changes. See the Handling Runtime Changes guide for more details.

Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents