Android: what is the best way to show a TextView in case if no item in a ListView?
I need to show a list of items, the items are read from a database, and it is possible there is no item, in this case, I开发者_JAVA百科 just want to show a TextView saying "there is no item", I think I could implement this by using relative layout, both list and text are in center of parent, they are displayed alternatively, but is there any way better than this?
Thanks!
Adding to Aleadam , Bill Mote
You may call at any time AdapterView.setEmptyView(View v) on an AdapterView object to attach a view you would like to use as the empty view.
The snippet is as follows:
empty = (TextView)findViewById(R.id.empty1);
list = (ListView)findViewById(R.id.list1);
list.setEmptyView(empty);
Make sure you keep the ListView and TextView inside the same parent.
For detailed description please refer this
If you're using a ListActivity, that is the default behavior. If not, then you can set the ListView visibility to GONE and a TextView visibility to VISIBLE.
Aleadam is right. Here's an example XML in support of his answer:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
<ListView
android:id="@+id/android:list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
<TextView
android:id="@id/android:empty"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:textColor="@drawable/red"
android:gravity="center_vertical|center_horizontal"
android:textStyle="bold"
android:text="@string/error_no_groups"
/>
</LinearLayout>
The first tutorial on the Android developer website explains how to do this: http://developer.android.com/resources/tutorials/notepad/notepad-ex1.html
(Look under Step 4)
Snippet:
- The ListView and TextView can be thought as two alternative views, only one of which will be displayed at once. ListView will be used when there are notes to be shown, while the TextView (which has a default value of "No Notes Yet!" defined as a string resource in res/values/strings.xml) will be displayed if there aren't any notes to display.
- The View with the empty id is used automatically when the ListAdapter has no data for the ListView. The ListAdapter knows to look for this name by default. Alternatively, you could change the default empty view by using setEmptyView(View) on the ListView.
精彩评论