Skip to content Skip to sidebar Skip to footer

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?

Solution 1:

Try this way any fragment to set argument and get argument..

// pass parameter to pass into bundlepublicstatic NewMessageFragment newInstance(UserData userData) {
    NewMessageFragmentnewMessageFragment=newNewMessageFragment();
    Bundlebundle=newBundle();
    bundle.putParcelable(Constants.KEY_MESSAGE_USER_VO, userData);
    newMessageFragment.setArguments(bundle);
    return newMessageFragment;
}

// get value.privatevoidextractArguments() {
    Bundlebundle= getArguments();
    if (bundle != null) {
        userData = bundle.getParcelable(Constants.KEY_MESSAGE_USER_VO);
    }
}

extractArguments() method called into onCreateView() method.

Solution 2:

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

Post a Comment for "Setarguments() In Fragment And Oncreate()"