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


的文档 Fragment.getContext() 说

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

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

这是 Application 要么 Activity  Context


5728
2017-09-08 03:39


起源

stackoverflow.com/questions/8215308/using-context-in-fragment - IntelliJ Amiya


答案:


简短的回答

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) 方法。


13
2017-09-08 07:01



令人沮丧的地狱。在很长一段时间内在android中引入的最有用的方法,但需要API 23,这意味着任何严肃的项目都不可能在至少几年内使用它。 - Bassinator


对于FragmentActivity和inherited - 'getContext()'仍然会返回活动上下文,如果你检查源代码,你可能会看到这个。


0
2017-09-08 04:09



你是对的,但问题是询问新的问题 Fragment#getContext(),不是 FragmentActivity#getContext()。 - ugo
我在说什么 Fragment#getContext() - dtx12