Best practice for instantiating a new Android Fragment

前端 未结 13 1517
暖寄归人
暖寄归人 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条回答
  •  -上瘾入骨i
    2020-11-21 05:07

    If Android decides to recreate your Fragment later, it's going to call the no-argument constructor of your fragment. So overloading the constructor is not a solution.

    With that being said, the way to pass stuff to your Fragment so that they are available after a Fragment is recreated by Android is to pass a bundle to the setArguments method.

    So, for example, if we wanted to pass an integer to the fragment we would use something like:

    public static MyFragment newInstance(int someInt) {
        MyFragment myFragment = new MyFragment();
    
        Bundle args = new Bundle();
        args.putInt("someInt", someInt);
        myFragment.setArguments(args);
    
        return myFragment;
    }
    

    And later in the Fragment onCreate() you can access that integer by using:

    getArguments().getInt("someInt", 0);
    

    This Bundle will be available even if the Fragment is somehow recreated by Android.

    Also note: setArguments can only be called before the Fragment is attached to the Activity.

    This approach is also documented in the android developer reference: https://developer.android.com/reference/android/app/Fragment.html

提交回复
热议问题