的文档 Fragment.getContext()
说
返回Fragment当前与之关联的上下文。
它是在api 23中引入的 http://developer.android.com/reference/android/app/Fragment.html#getContext()
这是 Application
要么 Activity
Context
?
的文档 Fragment.getContext()
说
返回Fragment当前与之关联的上下文。
它是在api 23中引入的 http://developer.android.com/reference/android/app/Fragment.html#getContext()
这是 Application
要么 Activity
Context
?
简短的回答
Fragment.getContext()
返回使用片段的活动的上下文
细节
自从api 23 in 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();
}
在片段中获取Activity的上下文之前,有几个步骤 getContext()
方法。
1)在Activity初始化期间 FragmentController
被建造:
final FragmentController mFragments = FragmentController.createController(new HostCallbacks());
2)它使用 HostCallbacks
class(内部类) 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)
方法。
对于FragmentActivity和inherited - 'getContext()'仍然会返回活动上下文,如果你检查源代码,你可能会看到这个。