Wednesday, July 28, 2010

ListView.setEmptyView() gotcha

When you set a ListView's "empty view" programmatically, you can end up scratching your head as to why your empty view actually doesn't appear when the list is empty.

If this happens, then what you forgot is that you must manually add your empty view to your view hierarchy, cos ListView won't do it for you. Although it's obvious when you think about it, the documentation doesn't mention this detail, and Googling shows at least one person had the problem.

Here's the code with the lines that it's all too easy to forget in bold...

TextView emptyView = new TextView(context);
emptyView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
emptyView.setText("This appears when the list is empty");
emptyView.setVisibility(View.GONE);
((ViewGroup)list.getParent()).addView(emptyView);
list.setEmptyView(emptyView);


1 comment: