1

In my app I have an activity with tabs used to manage 6 fragments . I have some fragments in which I must create some views programmatically based on some data I download from a webservice . How can I save the views I created programmatically and restore them in on resume of the fragments wihtout the need to recreate them every time ?

Marcel
  • 23
  • 4

1 Answers1

0

You should use singleton pattern for yours fragments.

A singleton in Java is a class for which only one instance can be created provides a global point of access this instance. The singleton pattern describe how this can be archived.

For example:

    public class YourFragment extends Fragment {
      private static YourFragment uniqInstance;

      private YourFragment () {
      }

      public static YourFragment getInstance() {
        if (uniqInstance == null) {
          uniqInstance = new YourFragment();
        }
        return uniqInstance;
      }
      .........
} 

When you want to access your fragment should call:

YourFragment.getInstance();

If you want to access method in your fragment should call:

YourFragment.getInstance().yourMethod();

Of course the method which you access must be declare public.

Hope it helps!

Ivan Ivanov
  • 902
  • 5
  • 12
  • 1
    Thank you for your answer , it is useful in some cases but it is not the optimal solution in my case . I was already calling the creation of the fragment only once . While I was waiting for answers I had found some sort of solution by my own . I had made the root view of the fragment a variable of the fragment itself and every time the OnCreateView is called i only inflate the view if the view is null , otherwise it returns the same view I had created previously . Now the problem is to update the views when i detect data update from the webservice – Marcel Mar 23 '16 at 10:03