Fragment as a singleton in Android

后端 未结 1 1044
借酒劲吻你
借酒劲吻你 2020-12-13 14:42

General Question Can I define Fragments as Singletons?

Specific question In my application I have one \'FragmentActivity\' with a

1条回答
  •  一整个雨季
    2020-12-13 15:10

    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
        }
    }
    

    0 讨论(0)
提交回复
热议问题