【问题标题】:How to get an ApplicationContext from createPackageContext()如何从 createPackageContext() 获取 ApplicationContext
【发布时间】:2016-01-22 02:18:47
【问题描述】:

代码如下:

上下文 c = getContext().createPackageContext("com.master.schedule", Context.CONTEXT_INCLUDE_CODE|Context.CONTEXT_IGNORE_SECURITY);

int id = c.getResources().getIdentifier("layout_main", "layout","com.master.schedule"); LayoutInflater inflater = LayoutInflater.from(c); piflowView = inflater.inflate(id, null);

com.master.schedule 是我的包项目。上面的代码显示了另一个项目(他的包名称与我的不同)如何膨胀我的项目,在我的项目中只有一个 ViewGroup(我没有活动);当我调用“context.getApplicationContext”时,它返回null...我的项目代码如下:

public class CascadeLayout extends RelativeLayout {
    private Context context;
    public CascadeLayout(Context context) {
        super(context);
        this.context=context.getApplicationContext();
    }
     @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        //here: context == null;
    }
}

我发现createPackageContext() 给我的“Context c”是ContextImpl 类型;我认为这是导致返回 null;

那么我怎样才能得到一个不为空的ApplicationContext呢?

BTW:请不要劝我不要调用getApplicationContext();因为我必须使用.jar,jar需要在其中调用getApplicationContext();

非常感谢。

【问题讨论】:

  • 你在调用什么对象getApplicationContext()?你也在你的代码中使用了错误的包......
  • 原谅我的英文表达,我已经更新了我的问题,我的 context.getApplicationContext();谢谢!

标签: android android-context


【解决方案1】:

createPackageContext() 的文档指出:

为给定的应用程序名称返回一个新的上下文对象。这个 上下文与命名应用程序获得的内容相同 已启动,包含相同的资源和类加载器。

从字里行间看,这个上下文显然应该与应用程序上下文“相同”。但是,您会看到它的getApplicationContext() 返回null,因此我们可以尝试使用ContextWrapper 来解决这个问题(见下文)。希望这种方法足以满足您的需求。

在以下代码中,WrappedPackageContext 用于包装 createPackageContext() 返回的“包上下文”,覆盖 getApplicationContext() 实现使其返回自身。

class WrappedPackageContext extends ContextWrapper {
    WrappedPackageContext(Context packageContext) {
        super(packageContext);
    }

    @Override
    public Context getApplicationContext() {
        return this;
    }
}

Context createApplicationContext(Context packageContext) {
    return new WrappedPackageContext(packageContext);
}

【讨论】:

  • 我是这样做的,现在它确实有效。谢谢你这么机智~
猜你喜欢
  • 1970-01-01
  • 2021-05-21
  • 1970-01-01
  • 1970-01-01
  • 2023-03-07
  • 1970-01-01
  • 2014-03-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多