Load resource (layout) from another apk

我怕爱的太早我们不能终老 提交于 2019-12-10 17:48:29

问题


I am wondering if it is possible to load a layout xml file from another apk. I know how to get access to another applications resources, but i am unsure how to load an xml if its even possible.

Would I have to parse the xml if I wanted to set that layout as a view using layout inflater?

Sort of like these steps...

  1. Use XmlPullParser.setInput to "load" the XML file
  2. Convert it to an AttributeSet
  3. Create a View from this AttributeSet
  4. use setContentView(View) in your Activity

I guess what i am asking, is this even possible? Like I said, i know how to access resources. But how would i access the layout xml?

Thanks!


回答1:


I managed to pull the layouts, and i add it to my viewflipper, however, there it is loaded as blank.

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;
    }
}

I get no errors, and i debugged and checked. The layout IDs are correct. However, in my viewFlipper its just blank. No warnings or errors i can find.

Finally got the solution... Have posted it below,

Load resource (layout) from another apk dynamically



来源:https://stackoverflow.com/questions/11324253/load-resource-layout-from-another-apk

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!