歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android中ListView分頁加載數據

Android中ListView分頁加載數據

日期:2017/3/1 11:10:20   编辑:Linux編程

Android應用開發中,采用ListView組件來展示數據是很常用的功能,當一個應用要展現很多的數據時,一般情況下都不會把所有的數據一次就展示出來,而是通過分頁的形式來展示數據,個人覺得這樣會有更好的用戶體驗。因此,很多應用都是采用分批次加載的形式來獲取用戶所需的數據。例如:微博客戶端可能會在用戶滑動至列表底端時自動加載下一頁數據,也可能在底部放置一個"查看更多"按鈕,用戶點擊後,加載下一頁數據。

下面通過一個Demo來展示ListView功能如何實現:該Demo通過在ListView列表的底部添加一個“查看更多...”按鈕來加載新聞(模擬新聞客戶端)分頁數據。同時限定每次加載10條記錄,但完全加載完數據後,就把ListView列表底部視圖“查看更多...”刪除。假設加載的數據總數為 38 條記錄。先看下該Demo工程的程序結構圖:


其中包 com.andyidea.bean中News.java類是新聞實體類,包com.andyidea.listview中paginationListViewActivity.java類是用來展示ListView列表。布局layout中包含三個布局文件,分別為:list_item.xml , loadmore.xml , main.xml 。下面分別貼下源碼:

layout中的 list_item.xml源碼:

  1. <span style="font-size:13px;"><?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout
  3. xmlns:android="http://schemas.android.com/apk/res/android"
  4. android:layout_width="fill_parent"
  5. android:layout_height="fill_parent"
  6. android:orientation="vertical">
  7. <TextView
  8. android:id="@+id/newstitle"
  9. android:layout_width="fill_parent"
  10. android:layout_height="wrap_content"/>
  11. <TextView
  12. android:id="@+id/newscontent"
  13. android:layout_width="fill_parent"
  14. android:layout_height="wrap_content"/>
  15. </LinearLayout></span>

layout中loadmore.xml源碼:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout
  3. xmlns:android="http://schemas.android.com/apk/res/android"
  4. android:layout_width="fill_parent"
  5. android:layout_height="fill_parent">
  6. <Button
  7. android:id="@+id/loadMoreButton"
  8. android:layout_width="fill_parent"
  9. android:layout_height="wrap_content"
  10. android:text="查看更多..." />
  11. </LinearLayout>
layout中main.xml源碼:
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation="vertical"
  4. android:layout_width="fill_parent"
  5. android:layout_height="fill_parent">
  6. <ListView
  7. android:id="@+id/lvNews"
  8. android:layout_width="fill_parent"
  9. android:layout_height="wrap_content"/>
  10. </LinearLayou
包 com.andyidea.bean中News.java類源碼:
  1. package com.andyidea.bean;
  2. /**
  3. * 新聞實體類
  4. * @author Andy.Chen
  5. * @mail [email protected]
  6. *
  7. */
  8. public class News {
  9. private String title; //標題
  10. private String content; //內容
  11. public String getTitle() {
  12. return title;
  13. }
  14. public void setTitle(String title) {
  15. this.title = title;
  16. }
  17. public String getContent() {
  18. return content;
  19. }
  20. public void setContent(String content) {
  21. this.content = content;
  22. }
  23. }
Copyright © Linux教程網 All Rights Reserved