Fragment as a singleton in Android

放肆的年华 提交于 2019-12-29 03:21:28

问题


General Question Can I define Fragments as Singletons?

Specific question In my application I have one 'FragmentActivity' with a FragmentPager which has two Fragments, FragmentA and FragmentB.

I defined the fragments as Singletons in the FragmentA extends Fragment class:

private static instance = null;

public static FragmentA getInstance() {
    if (instance == null) {
        instance = new FragmentA();
    }   
    return instance;
}
private FragmentA() {}

and in my FragmentPagerAdapter :

@Override
public Fragment getItem(int position) {
    switch(position){
    Fragment fragment = null;
    case 0:
        fragment = FragmentA.getInstance(); 
        break;
    case 1:
        fragment = FragmentB.getInstance(); 
        break;
    }
    return fragment;
}

and this is how I inflate the fragments layout:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    fragmentView = (RelativeLayout) inflater.inflate(R.layout.fragment_a_layout, container, false);
    return fragmentView;
}

My Problem:

When I first launch my app everything works well. When I close my app and then restart it, I'm not seeing both of the fragments.


回答1:


Fragments are meant to be reusable components of applications. You should not be using them as singletons, instead you should implement Fragment.SavedState or onSavedInstanceState.

public class YourFragment extends Fragment {
    // Blah blah blah you have a lot of other code in this fragment
    // but here is how to save state
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("curChoice", mCurCheckPosition);
    }
    @Override
    public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // savedInstanceState will have whatever you left in the outState bundle above
    }
}


来源:https://stackoverflow.com/questions/14839152/fragment-as-a-singleton-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!