Best practice for instantiating a new Android Fragment

前端 未结 13 1476
暖寄归人
暖寄归人 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 04:59

    Best practice to instance fragments with arguments in android is to have static factory method in your fragment.

    public static MyFragment newInstance(String name, int age) {
        Bundle bundle = new Bundle();
        bundle.putString("name", name);
        bundle.putInt("age", age);
    
        MyFragment fragment = new MyFragment();
        fragment.setArguments(bundle);
    
        return fragment;
    }
    

    You should avoid setting your fields with the instance of a fragment. Because whenever android system recreate your fragment, if it feels that the system needs more memory, than it will recreate your fragment by using constructor with no arguments.

    You can find more info about best practice to instantiate fragments with arguments here.

提交回复
热议问题