Fragment.getContext()的文档说
returns the context the Fragment is currently associated with.
它在api 23中介绍
http://developer.android.com/reference/android/app/Fragment.html#getContext()
这是应用程序还是活动上下文?
解决方法
简短答案
Fragment.getContext()返回使用片段的活动的上下文
细节
由于api 23在Fragment类中引入了mHost字段
// Activity this fragment is attached to. FragmentHostCallback mHost;
Fragment.getContext()使用它来获取上下文:
/**
* Return the {@link Context} this fragment is currently associated with.
*/
public Context getContext() {
return mHost == null ? null : mHost.getContext();
}
在片段的getContext()方法中获取Activity的上下文之前,有几个步骤.
1)在Activity初始化期间,创建FragmentController:
final FragmentController mFragments = FragmentController.createController(new HostCallbacks());
2)它使用HostCallbacks类(内部类的Activity)
class HostCallbacks extends FragmentHostCallback<Activity> {
public HostCallbacks() {
super(Activity.this /*activity*/);
}
...
}
3)您可以看到mFragments保留对活动上下文的引用.
4)当应用程序创建一个片段时,它使用FragmentManager.并且它的实例取自mFragments(自API级别23)
/**
* Return the FragmentManager for interacting with fragments associated
* with this activity.
*/
public FragmentManager getFragmentManager() {
return mFragments.getFragmentManager();
}
5)最后,Fragment.mHost字段设置在FragmentManager.movetoState(Fragment f,int newState,int transit,int transitionStyle,boolean keepActive)方法中.