Welcome 微信登录

首页 / 操作系统 / Linux / Android中ListView分页加载数据

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.  * 新闻实体类  
  5.  * @author Andy.Chen  
  6.  * @mail Chenjunjun.ZJ@gmail.com  
  7.  *  
  8.  */  
  9. public class News {  
  10.       
  11.     private String title;    //标题  
  12.     private String content;  //内容  
  13.       
  14.     public String getTitle() {  
  15.         return title;  
  16.     }  
  17.     public void setTitle(String title) {  
  18.         this.title = title;  
  19.     }  
  20.     public String getContent() {  
  21.         return content;  
  22.     }  
  23.     public void setContent(String content) {  
  24.         this.content = content;  
  25.     }  
  26.   
  27. }