Reputation: 4630
Suppose I have an application that receives an Android UI layout XML in the form of a string from a web service. Say for example, I received the following XML string...
<?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>
Is there anyway, that I could pass this string in as the layout to an activity and have it rendered ?
Upvotes: 2
Views: 1022
Reputation: 2946
As can be seen from the class overview here, layout inflation from a non-precompiled xml is not possible in Android at this time. I quote:
"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; it only works with an XmlPullParser returned from a compiled resource (R.something file.)"
Upvotes: 0
Reputation: 10368
I think you can create a XmlPullParser based on your String content. And then use the method from LayoutInflatoer:
inflate(XmlPullParser parser, ViewGroup root)
Please refer to the link http://developer.android.com/reference/android/view/LayoutInflater.html
Something like this:
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);
Upvotes: 1