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
Try it this way...
First a simple activity_main.xml layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<ListView
android:id="@+id/root_list"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1" />
<ViewStub
android:id="@+id/root_empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout="@layout/empty_view"
android:visibility="gone" />
</LinearLayout>
and from your MainActivity.java:
public class MainActivity extends Activity {
ListView mListView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.mListView = (ListView) findViewById(R.id.root_list);
mListView.setEmptyView(findViewById(R.id.root_empty));
mListView.setAdapter(null);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Whatever is placed in R.layout.empty_view
will appear whenever the adapter is null or isEmpty returns true.
I used this for the empty_view.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/empty_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="center"
android:background="@color/gray"
android:gravity="center"
android:text="@string/list_empty"
android:textColor="@color/white"
android:textSize="24sp" />
</LinearLayout>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With