我正在尝试通过 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/