Reputation: 1025
I want to understand correctly the difference between these ways of get a fragment from constructor:
public MyFragment(DataClass data) {
this.dataClass = data;
}
public static MyFragment newInstance(DataClass data) {
MyFragment fragment = new MyFragment();
fragment.setDataClass(data);
return fragment;
}
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.
Upvotes: 1
Views: 25
Reputation: 3627
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.
Upvotes: 1