Showing empty view when ListView is empty
I tried all the above solutions.I came up solving the issue.Here I am posting the full solution.
The xml file:
<RelativeLayout
android:id="@+id/header_main_page_clist1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="20dp"
android:paddingBottom="10dp"
android:background="#ffffff" >
<ListView
android:id="@+id/lv_msglist"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="@color/divider_color"
android:dividerHeight="1dp" />
<TextView
android:id="@+id/emptyElement"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="NO MESSAGES AVAILABLE!"
android:textColor="#525252"
android:textSize="19.0sp"
android:visibility="gone" />
</RelativeLayout>
The textView ("@+id/emptyElement") is the placeholder for the empty listview.
Here is the code for java page:
lvmessage=(ListView)findViewById(R.id.lv_msglist);
lvmessage.setAdapter(adapter);
lvmessage.setEmptyView(findViewById(R.id.emptyElement));
Remember to place the emptyView after binding the adapter to listview.Mine was not working for first time and after I moved the setEmptyView after the setAdapter it is now working.
Output:
It should be like this:
<TextView android:id="@android:id/empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="No Results" />
Note the id attribute.
When you extend FragmentActivity
or Activity
and not ListActivity
, you'll want to take a look at:
ListView.setEmptyView()
As appsthatmatter says, in the layout something like:
<ListView android:id="@+id/listView" ... />
<TextView android:id="@+id/emptyElement" ... />
and in the linked Activity:
this.listView = (ListView) findViewById(R.id.listView);
this.listView.setEmptyView(findViewById(R.id.emptyElement));
Does also work with a GridView...