Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android displaying text when ListView is empty

I'm setting a TextView with the id @android:id/empty to display a message when there are no items in the ListView. However, this TextView gets displayed even if there are items in the ListView, right before the items show up.

How can I make it such that it only gets displayed when there are no elements in the ListView?

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:orientation="vertical" >  <ListView     android:id="@android:id/list"     android:layout_width="wrap_content"     android:layout_height="fill_parent"     android:dividerHeight="1dp" > </ListView>  <TextView      android:id="@android:id/empty"     android:layout_width="wrap_content"     android:layout_height="wrap_content"     android:text="@string/empty_list" />  </LinearLayout> 

PS: I'm using a Loader and a SimpleCursorAdapter with a ListFragment.

like image 470
Daniel Avatar asked Apr 04 '12 18:04

Daniel


2 Answers

I'm guessing you are using a regular Fragment or Activity with a ListView inside of it. If you are, you must add the empty layout to the ListView manually.

E.g.

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

Then your ListView will automatically use this view when its adapter is empty

If you are using a ListActivity you do not need to call setEmptyView() on the ListView since the ListActivity automatically manages that for you.

like image 185
dymmeh Avatar answered Sep 20 '22 03:09

dymmeh


Set a TextView and assign to it whatever you want to display when the ListView is empty:

ProjectListAdapter projectListAdapter = new ProjectListAdapter(); TextView empty=(TextView)findViewById(R.id.empty); projectsListView.setEmptyView(empty); 

And in my xml file we write the below code

<TextView       android:id="@+id/empty"       android:layout_width="match_parent"       android:layout_height="wrap_content"       android:layout_gravity="center"       android:gravity="center"       android:text="Your text here"       android:textColor="#FFFFFF" /> 
like image 33
CoderDecoder Avatar answered Sep 18 '22 03:09

CoderDecoder