问题
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...
- Use XmlPullParser.setInput to "load" the XML file
- Convert it to an AttributeSet
- Create a View from this AttributeSet
- 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