Android: Fragment’s new getContext() method is which context?

Short answer

Fragment.getContext() return the context of activity where fragment is used


Since api 23 in Fragment class was introduced mHost field

// Activity this fragment is attached to.
FragmentHostCallback mHost;

And Fragment.getContext() uses it for getting context:

 * Return the {@link Context} this fragment is currently associated with.
public Context getContext() {
    return mHost == null ? null : mHost.getContext();

There are several steps before you get Activity’s context in fragment’s getContext() method.

1) During Activity’s initialization FragmentController is created:

final FragmentController mFragments = FragmentController.createController(new HostCallbacks());

2) It uses HostCallbacks class (inner class of Activity)

class HostCallbacks extends FragmentHostCallback<Activity> {
    public HostCallbacks() {
        super(Activity.this /*activity*/);

3) As you can see mFragments keep the reference to the activity’s context.

4) When the application creates a fragment it uses FragmentManager. And the instance of it is taken from mFragments (since API level 23)

 * Return the FragmentManager for interacting with fragments associated
 * with this activity.
public FragmentManager getFragmentManager() {
    return mFragments.getFragmentManager();

5) Finally, the Fragment.mHost field is set in FragmentManager.moveToState(Fragment f, int newState, int transit, int transitionStyle, boolean keepActive) method.

Leave a Comment