使用listView或者gridView时,当列表为空时,有时需要显示一个特殊的empty view来提示用户,一般情况下,如果你是继承ListActivity,只要
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/list_view" />
<TextView
android:id="@+id/empty_list_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="List view is empty"
android:visibility="gone" />
</LinearLayout>
这种布局,当列表为空当列表为空时就会自动显示TextView
如果继承Activity的话,想出现上面的效果,就需要手动
ListView list= (ListView)findViewById(R.id.mylist);
TextView tv= (TextView)findViewById(R.id.myempty);
list.setEmptyView(tv);
这是因为setEmptyView这个方法的设置是有限制的,就是设置的View必需在当前的View hierarchy里,亦即这个View需要被add到当前View hierarchy的一个结点上,如果没有添加到结点上的话,调用setEmptyView(View v)是没有任何效果的
还可以这样
TextView emptyView = new TextView(context);
emptyView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
emptyView.setText( This appears when the list is empty );
emptyView.setVisibility(View.GONE);
((ViewGroup)list.getParent()).addView(emptyView);
list.setEmptyView(emptyView);
或者
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
inflater = getLayoutInflater();
emptyView = inflater.inflate(R.layout.empty_view, null);
addContentView(emptyView, new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
list.setEmptyView(emptyView);
这几个方法都是将emptyview加入到当前view hierarchy上