Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to toggle Android ListView Empty Text?

So I have a ListView with an empty list catch in the XML. It works fine. I set the TextView on the ID to be the empty list for different cases, so I need to be able to programatically change that text.

<ListView
    android:id="@android:id/list"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
/>
<TextView android:id="@android:id/empty"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/no_data"
/>

I would like to have something like this but it won't work:

TextView empty = (TextView)listing.findViewById(android.R.id.empty);
empty.setText(R.string.no_display_data);

Any ideas?

like image 396
Du3 Avatar asked Jul 09 '11 12:07

Du3


2 Answers

Assuming you are in a ListActivity, do

TextView empty = getListView().getEmptyView();
empty.setText(R.string.no_display_data);

you can also possibly do (edit - the following is not correct)

TextView empty = (TextView)listing.findViewById(R.id.empty); //remove android
empty.setText(R.string.no_display_data);
like image 73
Gallal Avatar answered Oct 20 '22 02:10

Gallal


I usually set the visibility of the list to View.INVISIBLE when it has no content. And when there is content it is set to View.VISIBLE (through the .setVisibility(int)-method).

See the Android reference.


Sorry - I misread the actual question. The answer is still somewhat useful though - it stays for now.

You need to make a change to the ID-declaration in your XML. To something on the form "@+id/empty" then you'll be able to use the second code snippet you provided.

UPDATE: You should call the .setEmptyView(View)-method on you ListView to enable the magic.

like image 3
Michael Banzon Avatar answered Oct 20 '22 04:10

Michael Banzon