2012-07-04 45 views
3

我想知道是否可以从另一个apk加载布局XML文件。我知道如何访问其他应用程序资源,但我不确定如何加载xml,如果它甚至可能。从另一个apk加载资源(布局)

如果我想使用layout inflater将该布局设置为视图,我需要解析xml吗?

有点像这些步骤......

  1. 使用XmlPullParser.setInput到 “负载” 的XML文件
  2. 将其转换为AttributeSet中的
  3. 从这个AttributeSet中的
  4. 使用创建视图你的活动中的setContentView(View)

我猜我在问什么,这甚至有可能吗?就像我说的,我知道如何访问资源。但是,我将如何访问布局xml?

谢谢!

回答

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是正确的。但是,在我看来,它只是空白。没有警告或错误,我可以找到。

终于得到了解决......已经发布了它的下方,

Load resource (layout) from another apk dynamically

+1

欢迎的StackOverflow!如果遇到问题,请自行创建问题,并根据需要参考此问题。 –