我很困惑为什么我们在android中使用attachBaseContext。如果有人可以向我解释相同的含义,那将是一个很大的帮助。
attachBaseContext
函数是ContextWrapper
类,确保上下文只附加一次。 ContextThemeWrapper
作为其名称,应用来自应用程序或活动的主题,在android:theme
文件中定义为AndroidManifest.xml
。由于Application和Service都不需要主题,因此它们直接从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.
ContextWrapper类用于将任何上下文(应用程序上下文,活动上下文或基本上下文)包装到原始上下文中而不会打扰它。考虑以下示例:
override fun attachBaseContext(newBase: Context?) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase))
}
这里,newBase是原始上下文,它由CalligraphyContextWrapper类的wrap方法包装,它返回ContextWrapper类的实例。现在,修改后的上下文通过调用super.attachBaseContext()传递给ContextWrapper,后者是Activity的间接超类。现在我们可以访问书法依赖的背景以及我们的原始背景。 基本上,如果您想在当前活动,应用程序或服务中使用其他一些上下文,那么请覆盖attachBaseContext方法。 PS: 书法只是获得自定义字体calligraphy的依赖 查看此内容以了解有关上下文dive deep into context的更多信息 关于attachBaseContext的官方文档并不彻底,但你会对它有一个初步的想法.ContextWrapper