android - 我可以通过 setContentView 显示变量中的 XML 吗?

标签 android xml layout

我正在尝试通过 XSLT 将 XML 文件转换为 Android 布局 XML。到目前为止,我已经成功了,它返回了有效的 XML。我希望通过 setContentView 显示此输出(或者如果这不可能,我想将 View 添加到 ViewFlipper。到目前为止,我还没有成功,而且我也找不到有关此主题的任何信息。

这是我的代码:

Source xmlSource = new StreamSource(projectFile); //a XML file on the SD card
Source xsltSource = new StreamSource(getResources().openRawResource(R.raw.session));
TransformerFactory transFact = TransformerFactory.newInstance();
Transformer trans = transFact.newTransformer(xsltSource);

OutputStream output = new StringOutputStream();
StreamResult result = new StreamResult(output);
trans.transform(xmlSource, result);

output.toString() 以字符串格式返回转换后的 XML,到目前为止一切正常!但是如何在我的布局中使用此 XML? 我尝试过以下方法:

setContentView(output);

和:

projectFlipper = (ViewFlipper)findViewById(R.id.projectFlipper);
projectFlipper.addView(output);

我尝试过转换该变量,但我已经卡住了很长一段时间了。我在忽略什么?还是没有办法做到这一点?

提前致谢!

最佳答案

事实上, View 是使用 LayoutInflater 通过 XML 文件创建的。但是,正如此类的 javadoc 中所述:

Important : For performance reasons, view inflation relies heavily on pre-processing of XML files that is done at build time. Therefore, it is not currently possible to use LayoutInflater with an XmlPullParser over a plain XML file at runtime.

因此,如您所见,不可能动态使用 XML 文件来创建新 View 。但是,您应该能够转换“转换”逻辑,以便以编程方式创建屏幕。

关于android - 我可以通过 setContentView 显示变量中的 XML 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4377297/

相关文章:

html - 将按钮置于 div 容器内居中

android - RingShapeDrawable 的半径设置为父级的高度而不是宽度

android - 无法加载 CascadeClassifier

c++ - 从 'mapped_type' 没有可行的转换

android - 是否可以构建此 iPhone 应用程序? (电话使用/消费监控)

c# - 从 XmlDocument 中删除子节点并包括元素的父节点

java - 在 Eclipse 中从 XML 生成 Java 代码

qt - 如何根据布局大小更新 QGridLayout 行/列数?

android - 为 AppBarLayout 设置高度时工具栏消失

android - 使用 OrmLite 在 Sqlite 中组合删除语句的帮助不大