Android:Fragment的新getContext()方法是哪个上下文? [英] Android: Fragment's new getContext() method is which context?

查看:53
本文介绍了Android:Fragment的新getContext()方法是哪个上下文?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Fragment.getContext()的文档说

返回Fragment当前与之关联的上下文.

returns the context the Fragment is currently associated with.

它是在api 23中引入的 http://developer.android.com/reference/android/app/Fragment.html#getContext()

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

这是 Application 还是 Activity Context ?

推荐答案

简短答案

Fragment.getContext()返回使用片段的活动的上下文

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

详细信息

由于引入了 Fragment 类中的api 23 mHost 字段

Since api 23 in Fragment class was introduced mHost field

// Activity this fragment is attached to.
FragmentHostCallback mHost;

然后 Fragment.getContext()使用它来获取上下文:

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();
}

在片段的 getContext()方法中获取Activity的上下文之前,需要执行几个步骤.

There are several steps before you get Activity's context in fragment's getContext() method.

1)在Activity的初始化期间,创建了 FragmentController :

1) During Activity's initialization FragmentController is created:

final FragmentController mFragments = FragmentController.createController(new HostCallbacks());

2)它使用 HostCallbacks 类( Activity 的内部类)

2) It uses HostCallbacks class (inner class of Activity)

class HostCallbacks extends FragmentHostCallback<Activity> {
    public HostCallbacks() {
        super(Activity.this /*activity*/);
    }
...
}

3)如您所见, mFragments 保留对活动上下文的引用.

3) As you can see mFragments keep the reference to the activity's context.

4)当应用程序创建片段时,它使用 FragmentManager .它的实例取自 mFragments (自API级别23起)

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)最后,在 FragmentManager.moveToState(Fragment f,int newState,inttransit,int transitionStyle,boolean keepActive)方法中设置 Fragment.mHost 字段.

5) Finally, the Fragment.mHost field is set in FragmentManager.moveToState(Fragment f, int newState, int transit, int transitionStyle, boolean keepActive) method.

这篇关于Android:Fragment的新getContext()方法是哪个上下文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆