从另一个apk加载资源(layout)

3
我想知道是否可以从另一个apk文件中加载布局xml文件。我知道如何访问另一个应用程序的资源,但我不确定如何加载xml文件,如果这样做是可能的话。
如果我想使用布局膨胀器将该布局设置为视图,那么我需要解析xml吗?
就像以下步骤一样...
1. 使用XmlPullParser.setInput来“加载”XML文件 2. 将其转换为AttributeSet 3. 从此AttributeSet创建View 4. 在您的Activity中使用setContentView(View)
我猜我要问的是,这是否可能?就像我说的,我知道如何访问资源。但我如何访问布局xml?
谢谢!
1个回答

3
我成功地获取了布局,并将其添加到我的ViewFlipper中,但是它加载为空白。
Resources packageResources;
Context packageContext;
try
{   
    packageResources = pm.getResourcesForApplication(packageName);
    packageContext = this.createPackageContext(packageName,  Context.CONTEXT_INCLUDE_CODE + Context.CONTEXT_IGNORE_SECURITY);                
}
catch(NameNotFoundException excep)
{
    // the package does not exist. move on to see if another exists.
}

Class layoutClass;
try
{
   // using reflection to get the layout class inside the R class of the package
   layoutClass = packageContext.getClassLoader().loadClass(packageName + ".R$layout");
}
catch (ClassNotFoundException excep1)
{
   // Less chances that class won't be there.
}

for( Field layoutID : layoutClass.getFields() )
{
   try
   {
       int id = layoutID.getInt(layoutClass);
       XmlResourceParser xmlResourceLayout = packageResources.getLayout(id);

       View v = new View(this, Xml.asAttributeSet(xmlResourceLayout));

       this.viewFlipper.addView(v);                 
    }
    catch (Exception excep)
    {
        continue;
    }
}

我没有收到任何错误信息,并进行了调试和检查。布局ID是正确的。然而,在我的viewFlipper中,它只是空白的。我找不到任何警告或错误。
最终找到了解决方案...已经在下面发布了, 从另一个apk动态加载资源(布局)

1
欢迎来到StackOverflow!如果您遇到问题,请创建自己的问题并在必要时引用此问题。 - Ashley Ross

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接