Home Android ListView, show a message if the list is empty
Post
Cancel

Android ListView, show a message if the list is empty

This solution was found on StackOverflow as an answer to this question: Android ListView,show a message if arrayList of arrayAdapter is empty.

The common way is setting an empty textview (@android:id/empty) after the listview:

layout/activity_main.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?xml version="1.0" encoding="utf-8"?>
<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="@android:id/list"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:dividerHeight="1dp" >
</ListView>

<TextView
    android:id="@android:id/empty"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/empty_list" />

</LinearLayout>

And then set set the empty view to the listview:

MainActivity.java

1
2
3
ListView lv = (ListView)findViewById(android.R.id.list);
TextView emptyText = (TextView)findViewById(android.R.id.empty);
lv.setEmptyView(emptyText);

This should show items in the list whenever they are, and show the textview when not.

This post is licensed under CC BY 4.0 by the author.