http://hi.baidu.com/iceliushuai/item/2761f44666cf9ae2bdf45119
關鍵字: ListView EmptyView setEmptyView
最新開發一個應用程式,需要用到當ListView為空白時設定一些View來顯示提示內容。我們已經知道ListView有一個公開的方法:setEmptyView(View v)
可是這個方法的設定是有限制的,就是設定View必需在當前的View hierarchy裡,亦即這個View需要被add到當前一個View Tree的一個結點上,如果沒有添加到結點上的話,調用setEmptyView(View v)是沒有任何效果的。
它的過程大概是:
ListView listview = (ListView) findViewById(R.id.list);View emptyView = findViewById(R.id.empty);ViewGroup parentView = (ViewGroup) listview.getParent();parentView.addView(newEmptyView, 2); // 你需要在這兒設定正確的位置,以達到你需要的效果。listview.setEmptyView(emptyView);
另:如果你直接設定在XML中也就不需要額外的添加到View Tree中了,因為它已經在那兒了,比如你的Layout是
<?xml version="1.0" encoding="UTF-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="fill_parent"android:layout_height="fill_parent"android:gravity="center_vertical"android:orientation="vertical" ><include layout="@layout/fixed_headerview" /><ListViewandroid:id="@+id/list"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_weight="1"android:drawSelectorOnTop="false"android:fastScrollEnabled="true"android:textSize="18sp" /><TextViewandroid:id="@+/empty"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_weight="1"android:gravity="center"android:padding="15dip"android:text="@string/text_no_song"android:textSize="22sp"android:visibility="gone" /></LinearLayout>
那你只需要以下的代碼就可以了:
ListView listview = (ListView) findViewById(R.id.list);View emptyView = findViewById(R.id.empty);listview.setEmptyView(emptyView);