0

Hi I'm learning now about Fragments and I have some doubts.

V1: So the correct way to create a new Fragment should be with "newInstance" instead of a constructor and would be something like this:

    Fragment fragment = MyFragment.newInstance(variable);

And the code on the class "MyFragment" should be this:

private static final String ARG_PARAM1 = "param1";
private int variable;
public MyFragment() {
    //Empty constructor
}

New instance will receive the param and will put them on a Bundle and set the argument for the class

 public static mi_fragment newInstance(Int param1) {
    MyFragment fragment = new MyFragment();
    Bundle args = new Bundle();
    args.putInt(ARG_PARAM1, param1);
    fragment.setArguments(args);
    return fragment;
}

Then after setting it the method onCreate will pick up the argument:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        variable = getArguments().getInt(ARG_PARAM1);
    }

V2: But I still can't see the problem with using the constructor and setting the arguments programatically:

 Bundle bundle = new Bundle();
 bundle.putInt("key", variable);
 
 Fragment fragment = new MyFragment();
 fragment.setArguments(bundle);

Then I pick up the argument on the method onCreate:

public void onCreate(@Nullable Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    Bundle bundle = this.getArguments();
    if(bundle!=null){
        variable = getArguments().getInt("key");
    }
}

So I decided to search on the internet about this and I found a good answer but I still can't seem to understand it or when you could use it.

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.

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

So my conclusion is that you keep the bundle alive and using the newInstance could make you return to the last fragment for example. But probably I'm wrong so I need help.

Question: What's the main difference between both and how do you benefit from newInstance ? An example.

Community
  • 1
  • 1
Barrufet
  • 495
  • 1
  • 11
  • 33
  • 1
    there is no difference. but newInstance is cleaner – Hooman Feb 08 '20 at 15:28
  • So, everyone is freaking out when there's no really difference? @Hooman – Barrufet Feb 08 '20 at 15:35
  • 1
    everyone is against using fragment constructor for passing data not using newInstance or local method – Hooman Feb 08 '20 at 16:36
  • 1
    I think , a class should be self sufficient . For this , when you create a newIntance method in fragment , this method will itself take care of creating a fragment and passing arguments to it. On the contrary , if you do the later , you are creating a fragment and pass the arguments. So , i agree with @Hooman . First way is cleaner – ROHIT LIEN Feb 10 '20 at 08:11

0 Answers0