I have a problem with the setEmptyView method from a ListView.
Here is my Java code:
ListView view = (ListView)findViewById(R.id.listView1);
view.se
also these two methods helped me with displaying empty view:
adapter.notifyDataSetChanged();
list.invalidateViews();
I have just been learned android, but the snippet from https://developer.android.com/guide/topics/ui/layout/listview.html depicts some different approach:
// Create a progress bar to display while the list loads
ProgressBar progressBar = new ProgressBar(this);
progressBar.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, Gravity.CENTER));
progressBar.setIndeterminate(true);
getListView().setEmptyView(progressBar);
// Must add the progress bar to the root of the layout
ViewGroup root = (ViewGroup) findViewById(android.R.id.content);
root.addView(progressBar);
ViewGroup root = (ViewGroup) findViewById(android.R.id.content);
There are some correct solutions, but I think this is the best approach!
View emptyView = getLayoutInflater().inflate(R.layout.empty_list_cart, null);
addContentView(emptyView, listView.getLayoutParams()); // You're using the same params as listView
listView.setEmptyView(emptyView);
listView.setAdapter(adapter);
The core of the problem is that the AdapterView class does not actually add the view you pass to setEmptyView() to any container. It just changes the visibility. There are lots of ways to put your "empty view" object into a container, as the other answers describe.
The documentation for AdapterView should really be updated to reflect this, since it is not obvious.
Just use,
View emptyView = getLayoutInflater().inflate(R.layout.empty_view, null);
((ViewGroup)listView.getParent()).addView(emptyView);
Instead of listView.setEmptyView(emptyView);
The simplest way to use setEmptyView()
is with your "empty" TextView and ListView in the same layout like this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/empty_list_item"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/emptyList"
android:visibility="gone" />
</LinearLayout>
Now you can use:
view.setEmptyView(findViewById(R.id.empty_list_item));