ListView中没有要显示的数据时,我们可以显示一个布局用于提示用户没有数据,通常可以直接使用listview.setEmptyView设置一个view。
但设置的View必需在当前的View hierarchy里,亦即这个View需要被add到当前Viewhierarchy的一个结点上,如果没有添加到结点上的话,调用setEmptyView(View v)是没有任何效果的。大致流程是这样的:
TextView emptyView = new TextView(context);
((ViewGroup)listView.getParent()).addView(emptyView);
listView.setEmptyView(emptyView);
即先把emptyview添加到listview的父控件中。
但直接在布局中这样写的话就不需要手动添加到父控件中了,因为布局实例化后已经在了。
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/listView"/>
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/iv"
android:src="@drawable/pic"/>
</FrameLayout>
listView=(ListView) findViewById(R.id.listView);
ImageView emptyView=(ImageView) findViewById(R.id.iv);
listView.setEmptyView(emptyView);
这样当adaper为null或没有数据时就会显示imageview了