views:

78

answers:

2

Hello. 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.

A: 

Hmm, maybe the reason is that the view doesn't have the layout params set. Try to set some layout params to that view, and i think that will work. Something like this:

emptyListText.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));

If this doesn't work, try to inflate the view in your ListView's parent (R.id.list), with something like this:

mEmptyListView = (LinearLayout) getLayoutInflater().inflate(
                R.layout.no_items,
                (LinearLayout) findViewById(R.id.list));
mListView.setEmptyView(findViewById(R.id.no_items));

I'm writing it from memory, so let me know if it doesn't work or there is any typo. Basically the idea is that your view should be added to the layout

Ger

ggomeze
Thanks for your suggestion but its still not working.
MyNameIsZero
Ok, i edited my answer. Let me know if this works for you...
ggomeze
+1  A: 

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

McStretch
@MyNameIsZero: Did our answers help or are you still having issues?
McStretch