Android ListView无数据项时提示

时间:2023-03-09 16:03:55
Android ListView无数据项时提示

只需要调用在代码中调用setEmptyView(View emptyView)设置ListView为空时显示这个TextView即可。

布局文件

<?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" > <ListView
android:id="@+id/myList"
android:layout_width="match_parent"
android:layout_height="match_parent" /> <!-- Here is the view to show if the list is emtpy --> <TextView
android:id="@+id/myText"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="No items." /> </LinearLayout >

实现

private ListView mListView = null;

mListView = (ListView) findViewById(R.id.myList);
mListView.setEmptyView(findViewById(R.id.myText)); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, generateStrings()); mListView.setAdapter(adapter);

扩展:

  因为setEmptyView(View emptyView)这个方法是属于AdapterView这个类的,所以除了ListView之外,其他的子类,如GridView,Spinner等,应该也可以用这个方法来设置Adapter数据为空时显示另一个View。