passing context as argument of DialogFragment

giozh picture giozh · Mar 17, 2013 · Viewed 27.5k times · Source

it's possible to pass a context variable to a DialogFragment?

i've use this code inside dialog for passing a string:

public static ConfirmDialog newInstance( String f) {
    ConfirmDialog d = new ConfirmDialog();

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

    return d;
}

but i don't find any function like putString for passing context. It's possible to do that?

Answer

A--C picture A--C · Mar 17, 2013

Your DialogFragment has a very handy method for getting a Context instance:

getActivity()

Fragment#getActivity() will return the instance of the Activity (which is a Context) that the Fragment is attached to. Use it after the Fragment's onAttach() is called. The below chart illustrates the Fragment lifecycle, as you can see, using getActivity() from onCreate() to onDestroy() should be a valid call.

enter image description here

For more information, read the Fragment documentation