1

I want to understand correctly the difference between these ways of get a fragment from constructor:

1

public MyFragment(DataClass data) {
this.dataClass = data;
}

2

public static MyFragment newInstance(DataClass data) {
MyFragment fragment = new MyFragment();
fragment.setDataClass(data);
return fragment;
}

3

public static MyFragment newInstance(DataClass data) {
MyFragment fragment = new MyFragment();

Bundle args = new Bundle();
args.putInt("myData", data.getData());
fragment.setArguments(args);

return fragment;
}

Thanks in advance.

Informatheus
  • 1,025
  • 1
  • 9
  • 20

1 Answers1

1

First of all, Fragment should have empty constructor only!

Please check documentation, there is stated:
"Every fragment must have an empty constructor...".

Then check this post for nice explanation.

About options ##2 and 3 - as for me, both are appropriate.

Via Bundle - again post mentioned above says, "This way if detached and re-attached the object state can be stored through the arguments.".

But if you create newInstance of Fragment every time - #2 approach is also good. I use #2 approach, cause I don't store created fragments.

Community
  • 1
  • 1
Goltsev Eugene
  • 3,325
  • 6
  • 25
  • 48