標籤:android android開發
在移動平台上為使用者展示資料的一個常用方法是將資料填充進一個List內,而此時需要注意的一點就是:
原文地址:(http://blog.csdn.net/vector_yi/article/details/24936163)
如何處理需要填充的資料為空白的情況? ListView及其他繼承自AdapterView的類都有一個簡便的處理這種情況的方法:setEmptyView(View)。 當ListView的Adapter為空白或者Adapter的isEmpty()方法返回true的時候,它將會把設定的emptyview繪製出來。
舉個栗子,假設我們需要建立一個應用來管理我們的待辦事項,我們的首頁面將會是一個用來展示這些待辦事項的ListView。 而當我們第一次載入進這個應用時,待辦事項必然為空白。此時我們就可以利用一個圖片或者一段描述性的話來表達“無待辦事項”。 看看XML布局檔案:
<FrameLayout xmlns:android = "http://schemas.android.com/apk/res/android" android:layout_width= "fill_parent" android:layout_height= "fill_parent" android:orientation= "vertical" > <ListView android:id ="@+id/my_list_view" android:layout_width ="fill_parent" android:layout_height ="fill_parent" /> <ImageView android:id ="@+id/empty_view" android:layout_width ="fill_parent" android:layout_height ="fill_parent" android:src ="@drawable/empty_view" /></FrameLayout>
再來看自訂的drawable/empty_view檔案:
<shape xmlns:android = "http://schemas.android.com/apk/res/android" android:shape= "rectangle" > <solid android:color= "#AA00FF00" /></shape>
是一個自訂的shape,當ListView沒資料的時候才展現出來。
最後再看MainActivity檔案:
public class MainActivity extends Activity { private ListView mListView; @Override public void onCreate (Bundle savedInstanceState ) { super. onCreate( savedInstanceState ); setContentView (R .layout .main ); mListView = (ListView ) findViewById (R .id .my_list_view ); mListView. setEmptyView (findViewById (R .id .empty_view )); /*String[] strs=new String[]{"1","2"}; ArrayAdapter<String> adapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,strs); mListView.setAdapter(adapter);*/ }}
僅僅建立一個ListView並設定了EmptyView為main.xml中建立的ImageView。注釋內的代碼用來測試當ListView有資料時,emptyview會不會顯示。
當然,你可以利用ViewStub來作為EmptyView,利用ViewStub可以消極式載入視圖,確保在不需要顯示EmptyView的時候它不會被渲染。關於ViewStub的用法,我在之前的博文《消極式載入和避免重複渲染》已進行過敘述。