11

The docs for Fragment.getContext() says it

returns the context the Fragment is currently associated with.

It was introduced in api 23 http://developer.android.com/reference/android/app/Fragment.html#getContext()

Is this the Application or Activity Context?

Rajesh Jadav
  • 12,801
  • 5
  • 53
  • 78
user2968401
  • 925
  • 3
  • 14
  • 27

2 Answers2

13

Short answer

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

Details

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.

Ilya Tretyakov
  • 6,848
  • 3
  • 28
  • 45
  • 2
    Frustrating as hell. The most useful method introduced in android in a long time, but requires API 23, which means any serious project is unlikely to use it for at least a few more years. – Bassinator Jul 07 '17 at 19:22
0

As for FragmentActivity and inherited - 'getContext()' still will return activity context, you may see this if you'll check a source code.

dtx12
  • 4,438
  • 1
  • 16
  • 12
  • You are correct, but the question is asking about the new `Fragment#getContext()`, not about `FragmentActivity#getContext()`. – ugo Sep 08 '15 at 04:23
  • I was talking about `Fragment#getContext()` – dtx12 Sep 08 '15 at 11:03