50個Android開發技巧(24 處理ListView數據為空的情況)


 在移動平台上為用戶展示數據的一個常用方法是將數據填充進一個List內,而此時需要注意的一點就是:
原文地址:(http://blog.csdn.net/vector_yi/article/details/24936163)

           如何處理需要填充的數據為空的情況?
   
      ListView及其他繼承自AdapterView的類都有一個簡便的處理這種情況的方法:setEmptyView(View)。
     當ListView的Adapter為空或者Adapter的isEmpty()方法返回true的時候,它將會把設置的emptyview繪制出來。
 
     舉個栗子,假設我們需要創建一個應用來管理我們的待辦事項,我們的主頁面將會是一個用來展示這些待辦事項的ListView。
     而當我們第一次載入進這個應用時,待辦事項必然為空。此時我們就可以利用一個圖片或者一段描述性的話來表達“無待辦事項”。
     看看XML布局文件:
[html]  view plain copy 在CODE上查看代碼片 派生到我的代碼片
 
  1. <FrameLayout xmlns:android = "http://schemas.android.com/apk/res/android"  
  2.    android:layout_width"fill_parent"  
  3.    android:layout_height"fill_parent"  
  4.    android:orientation"vertical" >  
  5.   
  6.    <ListView  
  7.        android:id ="@+id/my_list_view"  
  8.        android:layout_width ="fill_parent"  
  9.        android:layout_height ="fill_parent" />  
  10.   
  11.    <ImageView  
  12.        android:id ="@+id/empty_view"  
  13.        android:layout_width ="fill_parent"  
  14.        android:layout_height ="fill_parent"  
  15.        android:src ="@drawable/empty_view" />  
  16.   
  17. lt;/FrameLayout>  

再來看自定義的drawable/empty_view文件:
[html]  view plain copy 在CODE上查看代碼片 派生到我的代碼片
 
  1. <shape xmlns:android = "http://schemas.android.com/apk/res/android"  
  2.     android:shape"rectangle" >  
  3.     <solid android:color"#AA00FF00" />  
  4. </shape>  
     是一個自定義的shape,當ListView沒數據的時候才展現出來。

     最后再看MainActivity文件:
[java]  view plain copy 在CODE上查看代碼片 派生到我的代碼片
 
  1. public class MainActivity extends Activity {  
  2.   
  3.   private ListView mListView;  
  4.   
  5.   @Override  
  6.   public void onCreate (Bundle savedInstanceState ) {  
  7.     super. onCreate( savedInstanceState );  
  8.     setContentView (R .layout .main );  
  9.   
  10.     mListView = (ListView ) findViewById (R .id .my_list_view );  
  11.     mListView. setEmptyView (findViewById (R .id .empty_view ));  
  12.     /*String[] strs=new String[]{"1","2"}; 
  13.     ArrayAdapter<String> adapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,strs); 
  14.     mListView.setAdapter(adapter);*/  
  15.      
  16.   }  
  17.   
  18. }  

    僅僅創建一個ListView並設置了EmptyView為main.xml中創建的ImageView。注釋內的代碼用來測試當ListView有數據時,emptyview會不會顯示。
 
     當然,你可以利用ViewStub來作為EmptyView,利用ViewStub可以延遲加載視圖,確保在不需要顯示EmptyView的時候它不會被渲染。關於ViewStub的用法,我在之前的博文《延遲加載和避免重復渲染》已進行過敘述。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM