基于动态指定的XML呈现Android UI
假设有一个应用程序从web服务接收字符串形式的Android UI布局XML。例如,我收到以下XML字符串基于动态指定的XML呈现Android UI,android,user-interface,Android,User Interface,假设有一个应用程序从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
<?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>
无论如何,我是否可以将此字符串作为布局传递给活动并进行渲染?我认为您可以根据字符串内容创建XmlPullParser。然后使用LayoutInflatoer中的方法:
inflate(XmlPullParser parser, ViewGroup root)
请参考链接
大概是这样的:
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);
从类概述中可以看出,目前在Android中不可能从未预编译的xml扩展布局。我引述: “出于性能原因,视图膨胀在很大程度上依赖于生成时对XML文件的预处理。因此,当前不可能在运行时将LayoutInflater与XmlPullParser一起使用在普通XML文件上;它只与从编译的资源(R.something文件)返回的XmlPullParser一起使用。”