Best practice for instantiating a new Android Fragment

前端 未结 13 1519
暖寄归人
暖寄归人 2020-11-21 04:38

I have seen two general practices to instantiate a new Fragment in an application:

Fragment newFragment = new MyFragment();

and

<         


        
13条回答
  •  不思量自难忘°
    2020-11-21 05:05

    setArguments() is useless. It only brings a mess.

    public class MyFragment extends Fragment {
    
        public String mTitle;
        public String mInitialTitle;
    
        public static MyFragment newInstance(String param1) {
            MyFragment f = new MyFragment();
            f.mInitialTitle = param1;
            f.mTitle = param1;
            return f;
        }
    
        @Override
        public void onSaveInstanceState(Bundle state) {
            state.putString("mInitialTitle", mInitialTitle);
            state.putString("mTitle", mTitle);
            super.onSaveInstanceState(state);
        }
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle state) {
            if (state != null) {
                mInitialTitle = state.getString("mInitialTitle");
                mTitle = state.getString("mTitle");
            } 
            ...
        }
    }
    

提交回复
热议问题