dfasdflskladf
dfasdflskladf

Reputation: 101

setArguments() in Fragment and onCreate()

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?

Upvotes: 0

Views: 725

Answers (2)

Tiberiu Neagu
Tiberiu Neagu

Reputation: 84

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

Basic Communication between two fragments

Upvotes: 0

user4571931
user4571931

Reputation:

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.

Upvotes: 1

Related Questions