Magnus
Magnus

Reputation: 18778

How can getArguments() be called in onCreate() of a Fragment..?

Can someone explain how setArguments() works? I don't get it. I get how to use it, but I don't really understand how the code below can actually work:

public class MyDialogFragment extends DialogFragment{

    public static MyDialogFragment newInstance(String test) {
        MyDialogFragment f = new MyDialogFragment();

        Bundle args = new Bundle();
        args.putString("test", test);
        f.setArguments(args);

        return f;
    }       


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Log.d("DEBUG", getArguments().getString("test")); // This actually works!
    }

}

I would have thought that onCreate() got called before the call to setArguments(), but clearly it does not. Is this the way it is supposed to work, or is it just pure luck that the call to setArguments() gets executed before onCreate() on my particular device? Could the opposite happen under different circumstances (faster/slower/different device, etc.)?

Maybe someone can point me to an article that describes how the flow of events for this works? I don't see where onCreate() would get called in the code above, unless it is called asynchronously, which to me sounds like it would be risky to rely on getArguments() inside onCreate()...

Upvotes: 0

Views: 1761

Answers (2)

BladeCoder
BladeCoder

Reputation: 12949

onCreate() is a method that is only called later by the framework, after the Fragment has been attached to the Activity, as you can see in the Fragment Lifecycle.

Upvotes: 0

laalto
laalto

Reputation: 152867

Your newInstance() is a factory method you call yourself. It creates the Fragment object and sets the arguments on it.

The created fragment object is then passed to a fragment transaction which eventually makes the fragment lifecycle callbacks such as onCreate() to be invoked at appropriate times.

In case the framework needs to recreate your fragment e.g. due to an orientation change, it will use the no-arg constructor of the fragment and retain the arguments you have set on the object. newInstance() and such are useful when the fragment is created for the first time.

For documentation, the Fragment class documentation is a good starting point.

Upvotes: 2

Related Questions