如何在外部非Activity类(插件)中使用本地资源?

时间:2013-07-07 12:08:28

标签: android plugins dexclassloader

我正在尝试为我的Activity设计一个插件系统。为此,我创建了一个名为PluginClass的新类,在我的项目外部和一个不同的包中,我从我的主应用程序加载了DEXClassLoader。

我可以轻松地从主应用程序调用所有PluginClass方法,它工作正常。当我尝试访问PluginClass项目的资源时出现问题。让我解释一下:PluginClass将本地布局扩展为主活动对象,方法getInflatedBox就像这样:

public void getInflatedBox(ViewGroup root) {
        View.inflate(context, R.layout.boxeslayout, root);
        this.imgBoxX = (ImageView) root.findViewById(R.id.imgBoxX);
        this.imgNotify = (ImageView) root.findViewById(R.id.imgNotify);
        this.txtNotify = (TextView) root.findViewById(R.id.txtNotify);
        this.txtBoxXName = (TextView) root.findViewById(R.id.txtBoxXName);
        this.llShadow = (LinearLayout) root.findViewById(R.id.llShadow);
}

应该将布局“boxeslayout”扩展到根对象中,来自此活动的主要活动(我删除了try / catch以使其可读):

Method getInflatedBox = null;
BoxX root;
Class boxesPlugin = getPlugin();     // Another main activity method, 
                                     // where I obtain the class with DexClassLoader
pgItem = boxesPlugin.newInstance();
getInflatedBox = boxesPlugin.getMethod("getInflatedBox", ViewGroup.class);
getInflatedBox.invoke( pgItem, root );

其中BoxX是一个扩展LinearLayout的自定义类。

问题出现在这里:我将布局扩展到根实例,但不是我想要的布局。实际上,R.layout.boxeslayout访问本地主要活动资源,从碰巧具有相同id值的活动向根扩展到布局。

由于我的PluginClass不是活动,我不能使用context.getResources。知道如何强制插件类的方法来访问插件资源吗?

非常感谢你的帮助。

1 个答案:

答案 0 :(得分:1)

好的,不确定是否有人对此感兴趣,因为我在两周多的时间内观众人数很少,但我找到了一个解决方案,也许这对其他人来说可能很有用,所以我在这里发帖。 / p>

关键是我无法访问插件R类,所以我必须找到方法getInflatedBox:

Resources pgResources = null;
Context pgCtx = actContext.createPackageContext(packName, Context.CONTEXT_IGNORE_SECURITY);
pgResources = pgCtx.getResources();
int lLayoutID = pgResources.getIdentifier(layoutName, "layout", pgPackName);
View.inflate(pgCtx , lLayoutID, root);

其中actContext是调用主活动的上下文。

实际上,我通过从插件包pgPackName构建的本地上下文pgCtx获取了我希望通过膨胀获取指向插件实际资源的指针的正确ID。

希望这有帮助。