【问题标题】:Android: Fragment's new getContext() method is which context?Android:Fragment 新的 getContext() 方法是哪个上下文?
【发布时间】:2015-12-03 14:44:29
【问题描述】:

Fragment.getContext() 的文档是这样说的

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

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

这是Application 还是Activity Context

【问题讨论】:

标签: android fragment


【解决方案1】:

简答

Fragment.getContext()返回使用fragment的activity的上下文

详情

由于Fragment类中的api 23被引入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 中长期以来引入的最有用的方法,但需要 API 23,这意味着任何严肃的项目都不太可能使用它至少几年。
【解决方案2】:

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

【讨论】:

  • 你是对的,但问题是关于新的Fragment#getContext(),而不是FragmentActivity#getContext()
  • 我说的是Fragment#getContext()
猜你喜欢
  • 2011-09-26
  • 1970-01-01
  • 2020-01-20
  • 2023-04-01
  • 2011-09-07
  • 1970-01-01
  • 1970-01-01
  • 2013-09-14
  • 2019-11-27
相关资源
最近更新 更多