50個Android開發技巧(24 處理ListView資料為空白的情況)

來源:互聯網
上載者:User

標籤: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的用法,我在之前的博文《消極式載入和避免重複渲染》已進行過敘述。


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.