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;
}
Fragments introduce modularity and reusability into your activity's UI by allowing you to divide the UI into discrete chunks. Activities are an ideal place to put global elements around your app's user interface, such as a navigation drawer.
Traditionally, a Fragment instance could only be instantiated using its default empty constructor. This is because the system would need to reinitialize it under certain circumstances like configuration changes and the app's process recreation.
Fragment has many methods which can be overridden to plug into the lifecycle (similar to an Activity): onAttach() is called when a fragment is connected to an activity. onCreate() is called to do initial creation of the fragment. onCreateView() is called by Android once the Fragment should inflate a view.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With