Tuesday, September 27, 2011

Merge tag

Suppose you want to use dynamic views in your app, you can do it by creating in the code and inflating it based on the parameters. In my situation I have say 4 different types of views and I wanted to inflate it at run time based on an input. I felt it was a chore to create a separate class for each of the views. So ventured to use the merge tag instead:

So I created views like this in xml.

< merge
xmlns:android="http://schemas.android.com/apk/res/android">
< EditText
android:text="Hello World"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15sp"/> < /merge>




Then created a parent layout, something like this:

< LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:id="@+id/form_id"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
< /LinearLayout>



In the code, parent view is got from the following line

ViewGroup root = (ViewGroup)findViewById(R.id.form_id);


To add this merge view, all I had to do was

LayoutInflater inflater = LayoutInflater.from(this);
View v = inflater.inflate(R.layout.textedit, root, true);


Tada, textview was inflated and added to the root.
IMPORTANT: you have to use only the above inflate function to add merge layout to the parent layout. Other inflate functions will throw a runtime exception.
Also you have to pass only the layout id not the resource id, as this will also cause an exception.