Display a message when Listview is empty

Asked

Viewed 1,387 times

5

I have a Listadapter that extends a Basedapter that works perfectly. When it is empty I wanted a message to appear any.

Where to implement this validation?

1 answer

11


The implementation is very simple.

You only need to declare one TextView with android:id="@android:id/empty" in the layout where stated the ListView which will 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 the Activity that has this layout is derived(extends) from ListActivity Android will do the rest for you.

If derived from Activity/AppCompatActivity, will have to tell the ListView which the TextView that has that function.

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

In this case it is possible to use any type of View and can assign you another id that is not @android:id/empty.

  • Very Good! Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.