I’m prototyping an Android application, and am trying to define the UI before writing any Java code. The basic XML layout stuff works fine, but I can’t figure out how to add a ListView with contents. Adding the ListView inside a LinearLayout works fine, but I can’t add anything (not even another LinearLayout) as the contents of this ListView.
I tried the fairly obvious way of doing this:
<ListView android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="2">
<LinearLayout android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:text="Line One"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView android:text="Line Two"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView android:text="Line Three"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</ListView>
But it failed (at runtime) with an exception when trying to start the activity:
java.lang.UnsupportedOperationException: addView(View, LayoutParams) is not supported in AdapterView.
The SDK documentation for the XML layout language is fairly poor, and I can’t seem to find any obvious way to make this work. What am I missing?
Bonus question: is there a way to detect problems in the XML layout at build-time, instead of waiting for Android to throw an exception at runtime?
You can’t. Your best options are to either use the
ListViewelement with the attributeandroid:entriespointing to a an array resource(this will show a simpleListViewofStrings) or simulate theListViewby replacing it with aScrollViewand then add the content you want in theListViewas the content of theListView(but it should be something that simulates the rows and not separate content).I guess android already does that. Placing content in a
ListViewis ok in the xml layout(probably) because theListViewis aViewGroup, but later when android actually tries to add the content to theListViewit will fail, as the exception says, because the operation is unsupported.