2

假设我有一个应用程序以字符串形式从 Web 服务接收 Android UI 布局 XML。例如,我收到以下 XML 字符串...

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">
    <EditText android:id="@+id/edit_message"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:hint="@string/edit_message" />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button_send" />
</LinearLayout>

无论如何,我可以将此字符串作为布局传递给活动并渲染它吗?

4

2 回答 2

1

我认为您可以根据您的 String 内容创建一个 XmlPullParser 。然后使用 LayoutInflatoer 中的方法:

inflate(XmlPullParser parser, ViewGroup root)

请参考链接http://developer.android.com/reference/android/view/LayoutInflater.html

像这样的东西:

XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput( new StringReader ( "YOUR XML CONTENT" ) );
View rootView = inflate(xpp, null));
setContentView(rootView);
于 2013-08-19T04:38:00.047 回答
0

从这里的类概述中可以看出,目前在 Android 中无法使用非预编译的 xml 进行布局膨胀。我引用:

“出于性能原因,视图膨胀严重依赖于在构建时完成的 XML 文件的预处理。因此,目前无法在运行时将 LayoutInflater 与 XmlPullParser 一起用于纯 XML 文件;它只能与 XmlPullParser 一起使用从已编译资源(R.something 文件)返回。”

于 2014-03-10T13:11:33.840 回答