Reputation: 3193
What is the real difference between these two approaches?
1.I am using standard old-fashined bundle:
public static final Fragment newInstance(int val1, int val2) {
TestFragment f = new TestFragment();
Bundle bundle = new Bundle();
bundle.putInt("val1", val1);
bundle.putInt("val2", val2);
f.setArguments(bundle);
return f;
}
2.I am setting as instance members
public static final Fragment newInstance(int val1, int val2) {
TestFragment f = new TestFragment();
f.val1 = val1;
f.val2 = val2;
return f;
}
Upvotes: 7
Views: 652
Reputation: 81578
The arguments
bundle is retained along with the onSaveInstanceState(Bundle)
, while constructor parameters are not.
Similarly to what happens if you don't save out your fields to onSaveInstanceState()
in an Activity. Think of the arguments
bundle like an Intent, Intent
s are also retained across process death and configuration change.
Upvotes: 4
Reputation: 13458
In the first example, you've not actually set the fragment instance variables val1 and val2, so they remain uninitialized. Because of this, you'd be required to read back the bundle in onCreate to set the instance variables.
When the fragment instance is destroyed and re-created (e.g. due to a device rotation), the onCreate (or onCreateDialog for DialogFragments) can re-load the arguments using:
public void onCreate(Bundle savedInstanceState)
{
if (savedInstanceState != null)
{
Bundle args = getArguments();
val1 = args.getInt("val1");
val2 = args.getInt("val2");
}
}
and your state can be restored.
Upvotes: 7