Communication objects between multiple fragments in ViewPager

前端 未结 7 1306
不知归路
不知归路 2021-02-07 06:53

I have 5 fragments in ViewPager used to fill business object with several fields step by step, in each step some of those fields will be set. I\'ve read many articl

7条回答
  •  深忆病人
    2021-02-07 07:30

    I wouldn't recommend a global singleton. There are two main reasons:

    1. By definition, a singleton limits your app to a single instance of the main business object. If you (or a designer, or your boss's boss's boss) ever decide to have multiple of these ViewPagers at a time, you will have to change your architecture anyways.
    2. The "Android way of thinking" is to expect that your user may put your app in the background and use other apps before returning to your app. If the system decides to kill your app in the background, then your singleton memory object will be destroyed, and your user will have lost all of their progress. The correct Android way to save state is by keeping the state in an Activity or Fragment, saving it appropriately in onSaveInstanceState(), and restoring it in onCreate().

    All of the Fragments in the ViewPager can get a reference to the parent Activity via a call to getActivity(). Or if your ViewPager is within a Fragment, then all of the Fragments can access the parent Fragment via a call to getParentFragment(). You can then cast the result to the appropriate class (or better yet, interface) and make method calls to pass data back and forth. Keep track of your business data in the parent Activity/Fragment. This way, you don't need a global singleton

    For example,

    public class MyParentFragment extends Fragment {
    
      private String mPageOneData;
      private int mPageTwoData;
      private List mPageThreeData;
    
      public void setPageOneData(String data) {
        mPageOneData = data;
      }
    
      ...
    }
    
    public class PageOneFragment extends Fragment {
    
      private void sendDataToParent(String data) {
        Fragment f = getParentFragment();
        if (f != null && f instanceof MyParentFragment) {
          MyParentFragment parent = (MyParentFragment) f;
          f.setPageOneData(data);
        }
      }
    
    }
    

提交回复
热议问题