Best practice for instantiating a new Android Fragment

前端 未结 13 1543
暖寄归人
暖寄归人 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:10

    The only benefit in using the newInstance() that I see are the following:

    1. You will have a single place where all the arguments used by the fragment could be bundled up and you don't have to write the code below everytime you instantiate a fragment.

      Bundle args = new Bundle();
      args.putInt("someInt", someInt);
      args.putString("someString", someString);
      // Put any other arguments
      myFragment.setArguments(args);
      
    2. Its a good way to tell other classes what arguments it expects to work faithfully(though you should be able to handle cases if no arguments are bundled in the fragment instance).

    So, my take is that using a static newInstance() to instantiate a fragment is a good practice.

提交回复
热议问题