【问题标题】:Why use ContextWrapper directly in an Activity instead of implicit context from "this"为什么直接在 Activity 中使用 ContextWrapper 而不是“this”中的隐式上下文
【发布时间】:2015-07-13 11:23:30
【问题描述】:

通过一些所谓的“好”资源来了解 Android 中上下文处理的细节和技巧,我多次遇到一种我无法理解的模式。

当您同样可以很好地使用隐式上下文时,使用 ContextWrapper 有什么优势?

例如为什么在活动方法中使用以下内容(直接在活动类中定义)

...
ContextWrapper cw = new ContextWrapper(getApplicationContext())
File filesDir = cw.getFilesDir();
...

不仅仅是

...
File filesDir = getFilesDir();
...

尽管 getFilesDir() 是在 ContextWrapper 类中定义的,但 Activity 无论如何都是 ContextWrapper 的子类,因此您仍然可以直接访问该方法。

那么这种增加的复杂性解决了哪些潜在问题(我没有看到)?

【问题讨论】:

  • Application 也扩展了ContextWrapper

标签: android android-context


【解决方案1】:

我想说(我可能是错的)在您提出的场景(和上下文)中可能没有什么不同。 getApplicationContext().getFilesDir() 也可以很容易地使用。

但是,我相信ContextWrapper 在其他情况下可能有用。据我了解,这是适配器模式。您可能只想为某些方法提供不同的行为,同时将所有其他方法代理到您传入的原始上下文引用。

查看RemoteViews的这段代码:

// RemoteViews may be built by an application installed in another
// user. So build a context that loads resources from that user but
// still returns the current users userId so settings like data / time formats
// are loaded without requiring cross user persmissions.
final Context contextForResources = getContextForResources(context);
Context inflationContext = new ContextWrapper(context) {
    @Override
    public Resources getResources() {
        return contextForResources.getResources();
    }
    @Override
    public Resources.Theme getTheme() {
        return contextForResources.getTheme();
    }
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-27
    • 1970-01-01
    • 2016-04-06
    • 1970-01-01
    • 2014-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多