attachBaseContext的作用是什么?

时间:2018-08-09 06:14:16

标签: android android-context

我对为什么在Android中使用attachBaseContext感到困惑。如果有人可以向我解释同一含义,那将是一个很大的帮助。

2 个答案:

答案 0 :(得分:1)

attachBaseContext函数是ContextWrapper类,用于确保仅将上下文附加一次。 ContextThemeWrapper的名称,来自android:theme文件中定义为AndroidManifest.xml的应用程序或活动中的主题。                                                                                       由于应用程序和服务都不需要主题,因此它们直接从ContextWrapper继承。在活动,应用程序和服务启动期间,每次将创建一个新的ContextImpl对象,该对象在Context中实现功能。

public class ContextWrapper extends Context {
    Context mBase;

    public ContextWrapper(Context base) {
        mBase = base;
    }

    /**
     * Set the base context for this ContextWrapper.  All calls will then be
     * delegated to the base context.  Throws
     * IllegalStateException if a base context has already been set.
     * 
     * @param base The new base context for this wrapper.
     */
    protected void attachBaseContext(Context base) {
        if (mBase != null) {
            throw new IllegalStateException("Base context already set");
        }
        mBase = base;
    }

}

有关this.的更多信息

答案 1 :(得分:0)

ContextWrapper 类用于将任何上下文(应用程序上下文,活动上下文或基本上下文)包装到原始上下文中,而不会对其造成干扰。 考虑下面的示例:

override fun attachBaseContext(newBase: Context?) {
    super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase))
}  

此处, newBase 是由 CalligraphyContextWrapper 类的 wrap 方法包装的原始上下文,该方法返回的实例> ContextWrapper 类。现在,通过调用 super.attachBaseContext()将修改后的上下文传递给 Activity 的间接超类 ContextWrapper 。现在,我们可以访问书法依赖项的上下文以及原始上下文。
基本上,如果您想在当前活动,应用程序或服务中使用其他上下文,请覆盖 attachBaseContext 方法。
PS:
书法只是获取自定义字体calligraphy的依赖项
请查看此内容,以了解有关上下文dive deep into context
的更多信息 关于 attachBaseContext 的官方文档并不详尽,但是您会对此有一个初步的认识。ContextWrapper

相关问题