Android:Fragment的新的getContext()方法是哪个上下文?

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)方法中.

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...