If I create a new Fragment
and then I set arguments to it can I rely on those arguments always being available for me in the onCreate()
of the Fragment
? If yes, how do they do it? If not how I'am I supposed to communicate if they don't want us to write new constructors?
Asked
Active
Viewed 468 times
0

dfasdflskladf
- 101
- 1
- 6
-
`how do they do it` - how they do what? the arguments are available though the whole fragment's lifecycle – Blackbelt Dec 06 '18 at 13:37
-
@Blackbelt in my head I'm thinking `onCreate()` is immediately called so if I have the `setArguments()` on the next line how are they available still on the `onCreate()`? – dfasdflskladf Dec 06 '18 at 13:52
-
it is not . setArguments has to be called after you instante the fragment and before committing a transaction. onCreate gets called after you commit a transaction – Blackbelt Dec 06 '18 at 13:53
2 Answers
1
Try this way any fragment to set argument and get argument..
// pass parameter to pass into bundle
public static NewMessageFragment newInstance(UserData userData) {
NewMessageFragment newMessageFragment = new NewMessageFragment();
Bundle bundle = new Bundle();
bundle.putParcelable(Constants.KEY_MESSAGE_USER_VO, userData);
newMessageFragment.setArguments(bundle);
return newMessageFragment;
}
// get value.
private void extractArguments() {
Bundle bundle = getArguments();
if (bundle != null) {
userData = bundle.getParcelable(Constants.KEY_MESSAGE_USER_VO);
}
}
extractArguments() method called into onCreateView() method.
0
Yes, your arguments are avaialble in onCreate method. Please check it out this response in order to see how to pass arguments to fragments: How to transfer some data to another Fragment?
Another way to communicate with the fragment is via a interface that your activity is implementing and you pass it as a reference to your fragment, in onAttach method. More info: https://developer.android.com/training/basics/fragments/communicating

Tiberiu Neagu
- 84
- 4