Display a message when the ListView is empty

5

I have a ListAdapter that extends a BaseAdapter that works perfectly. When it is empty, I want a message to appear.

Where to implement this validation?

    
asked by anonymous 01.02.2014 / 19:45

1 answer

11

The implementation is very simple.

You only need to declare a TextView with android:id="@android:id/empty" in the layout where you declared the ListView to be managed by Adapter .

Layout:

 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
         android:orientation="vertical"
         android:layout_width="match_parent"
         android:layout_height="match_parent">

     <ListView android:id="@android:id/list"
               android:layout_width="match_parent"
               android:layout_height="match_parent"
               android:layout_weight="1"/>

     <TextView android:id="@android:id/empty"
               android:layout_width="match_parent"
               android:layout_height="match_parent"
               android:text="No data"/>
 </LinearLayout>

If Activity that has this layout is derived (extends) from ListActivity Android will do the rest for you.

If it is derived from Activity/AppCompatActivity , you have to tell ListView what TextView that has this function.

ListView list = (ListView) findViewById(android.R.id.list);
TextView emptyView = (TextView) findViewById(android.R.id.empty);
list.setEmptyView(emptyView);

In this case you can use any type of View and you can assign it another id other than @android:id/empty .

    
01.02.2014 / 22:14