1 public class MainActivity extends Activity { 2 private ListView listView; 3 private List<String> data = new ArrayList<String>(); 4 ArrayAdapter<String> adapter; 5 View footer; 6 7 @Override 8 public void onCreate(Bundle savedInstanceState) { 9 10 super.onCreate(savedInstanceState); 11 setContentView(R.layout.main); 12 13 footer = getLayoutInflater().inflate(R.layout.footer, null); 14 15 listView = (ListView) this.findViewById(R.id.listView); 16 listView.setOnScrollListener(new ScrollListener()); 17 18 data.addAll(DataService.getData(0, 20)); 19 adapter = new ArrayAdapter<String>(this, R.layout.listview_item, R.id.textView, data); 20 listView.addFooterView(footer);//添加页脚(放在ListView最后) 21 listView.setAdapter(adapter); 22 listView.removeFooterView(footer); 23 } 24 25 private int number = 20;//每次获取多少条数据 26 private int maxpage = 5;//总共有多少页 27 private boolean loadfinish = true; 28 29 private final class ScrollListener implements OnScrollListener{ 30 31 public void onScrollStateChanged(AbsListView view, int scrollState) { 32 Log.i("MainActivity", "onScrollStateChanged(scrollState="+ scrollState+ ")"); 33 } 34 35 public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { 36 Log.i("MainActivity", "onScroll(firstVisibleItem="+ firstVisibleItem+ ",visibleItemCount="+ 37 visibleItemCount+ ",totalItemCount="+ totalItemCount+ ")"); 38 39 final int loadtotal = totalItemCount; 40 int lastItemid = listView.getLastVisiblePosition();//获取当前屏幕最后Item的ID 41 42 if((lastItemid+1) == totalItemCount){//达到数据的最后一条记录 43 if(totalItemCount > 0){ 44 //当前页 45 int currentpage = totalItemCount%number == 0 ? totalItemCount/number : totalItemCount/number +1; 46 int nextpage = currentpage + 1;//下一页 47 if(nextpage <= maxpage && loadfinish){ 48 loadfinish = false; 49 listView.addFooterView(footer); 50 51 new Thread(new Runnable() { 52 public void run() { 53 try { 54 Thread.sleep(3000); 55 } catch (InterruptedException e) { 56 e.printStackTrace(); 57 } 58 List<String> result = DataService.getData(loadtotal, number); 59 handler.sendMessage(handler.obtainMessage(100, result)); 60 } 61 }).start(); 62 } 63 } 64 65 } 66 } 67 } 68 69 Handler handler = new Handler(){ 70 public void handleMessage(Message msg) { 71 data.addAll((List<String>) msg.obj); 72 adapter.notifyDataSetChanged();//告诉ListView数据已经发生改变,要求ListView更新界面显示 73 if(listView.getFooterViewsCount() > 0) listView.removeFooterView(footer); 74 loadfinish = true; 75 } 76 }; 77 78 }
1 public class DataService { 2 3 public static List<String> getData(int offset, int maxResult){//分页 limit 0,20 4 List<String> data = new ArrayList<String>(); 5 for(int i=0 ; i < 20 ; i++){ 6 data.add("ListView数据的分批加载"+ i); 7 } 8 return data; 9 } 10 }