【问题标题】:Load resource (layout) from another apk从另一个 apk 加载资源(布局)
【发布时间】:2012-07-04 16:08:18
【问题描述】:

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

如果我想使用布局充气器将该布局设置为视图,是否必须解析 xml?

有点像这些步骤...

  1. 使用 XmlPullParser.setInput “加载” XML 文件
  2. 将其转换为 AttributeSet
  3. 从此 AttributeSet 创建一个视图
  4. 在您的 Activity 中使用 setContentView(View)

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

谢谢!

【问题讨论】:

    标签: java android eclipse xml-parsing layout-inflater


    【解决方案1】:

    我设法拉出布局,并将其添加到我的 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 正确。但是,在我看来Flipper 只是空白。我找不到任何警告或错误。

    终于找到解决办法了……已经贴在下面了,

    Load resource (layout) from another apk dynamically

    【讨论】:

    • 欢迎来到 StackOverflow!如果您遇到问题,请创建自己的问题并在必要时参考此问题。
    猜你喜欢
    • 1970-01-01
    • 2020-04-13
    • 2012-07-02
    • 1970-01-01
    • 2015-02-19
    • 2014-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多