1
I recently asked myself a question, seemingly simple, that I could not answer and I did not find any concise answer. The question is simple: Why use Bundle instead of a set method to pass parameters from an Activity to a Fragment?
For example:
Case 1:
public static MyFragment getInstance(String myAttr){
MyFragment myFragment = new MyFragment();
myFragment.setMyAttr(myAttr);
return myFragment;
}
Case 2:
public static MyFragment getInstance(String myAttr){
MyFragment myFragment = new MyFragment();
Bundle bundle = new Bundle();
bundle.putString("myAttr", myAttr);
myFragment.setArguments(bundle);
return myFragment;
}
I always use Case 2 because in all the books I’ve read they use it and I’ve learned that way. But none of them explain why to use with Bundle. It would be because of the life cycle of Activity and Fragment or because of the use of Case 2?
EDIT:
Complementing the Ramaral response.
There is an example that makes it easy to understand why it is necessary to use Case 2 instead of Case 1.
Just do two activities, A and B for example. And give commit()
in a Fragment, instantiated as in case 1, in Activity A.
Go to developer options, enable "Don’t Keep activities" option.
Overwrite the method onSaveInstanceState
.
Navigate from Activity A to B and then go back to A, and check the Bundle that comes as a parameter of onSaveInstanceState
is always null.
Yes, it is because of the life cycle of Fragment himself. When he is recreated (and this will happen), his method (case 1) will not be called. You have it in your own documentation...
– itscorey