Saturday, May 14, 2011

Adding a simple empty view in a ListActivity

The Android documentation shows how to set an empty view in the ListView of a ListActivity using XML layout. Since I wanted only a simple TextView to be displayed, I wanted to avoid modifying my layout. Therefore, I decided to create a TextView programatically.

TextView lEmpty = new TextView(MyListActivity.this);
lEmpty.setText("No entry");
getListView().setEmptyView(lEmpty);
lEmpty.setVisibility(View.GONE);
((ViewGroup)getListView().getParent()).addView(lEmpty);

At first, I didn't included the last two lines. As a result, the empty view was not showed. First, because the empty view wasn't added to the ViewGroup of the ListView. Also, if the visibility isn't set to GONE, then the view will always be rendered visible. These two operations are handled automatically when using declarative XML views.

1 comment: