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
?
getContext():It returns the Context which is linked to the Activity from which it is called. This is useful when we want to call the Context from only the current running activity.
You can use the getActivity() method to get context or You can use getContext() method . View root = inflater.
To get a reference to the ApplicationContext in a Spring application, it can easily be achieved by implementing the ApplicationContextAware interface. Spring will automatically detect this interface and inject a reference to the ApplicationContext: view rawMyBeanImpl. java hosted by GitHub.
1 Answer. To get the context in a fragmented use getActivity(), which renders the activity associated with a fragment. The activity is a context (since Activity continues Context). thiscontext = container.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With