Call to ListView set The Empty method does not work (nothing is displayed when the list is empty)

advertisements

I have an Activity which contains a ListView defined in XML (its not subclassing the ListActivity class).

I want to display a message when the ListView is empty, so I tried doing so with the setEmptyView method:

listView = (ListView) findViewById(R.id.list);
TextView emptyListText = new TextView(this);
// also tried with the following line uncommented
// emptyListText.setId(android.R.id.empty);
emptyListText.setText(getString(R.string.EmptyList));
listView.setEmptyView(emptyListText);

But it is not working.

Any ideas?

Thanks.


You need to add the following two lines to your code after you call setText():

emptyListText.setVisibility(View.GONE);
((ViewGroup)listView.getParent()).addView(emptyListText);

If the visibility is not set to GONE (hidden), then the TextView will always be rendered visible. The second line places the TextView into the ListView's ViewGroup -- which is automatically handled when using declarative XML Views.


Source: http://www.littlefluffytoys.com/?p=74