public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { // 若已经显示到了最后一条记录,则尝试继续更新记录。 if(firstVisibleItem + visibleItemCount == totalItemCount){ // 计算下一页的页号。 int nextPage = totalItemCount/pageSize + 1 ; if(nextPage != currentPage){ // 更新当前页,以免开启第二个线程,重复加载数据。 // nextPage是根据totalItemCount来计算的,若第一个线程没有加载完毕,则totalItemCount的值是不会改变的,因此当用户再次滑动滚动条到末尾时,由于totalItemCount的值没更改,所以nextPage的值也没有变,这样就保证了数据不会被加载两遍。 currentPage = nextPage; // 开始加载数据。 new MyAsyncTask().execute(); } } } |
语句解释:
|- 为了页面清晰,本范例仅仅将核心代码列出来。 |- 变量currentPage代表当前已经加载了多少页的数据。默认值为0 。 |- 变量nextPage代表将要加载哪一页的数据。变量pageSize代表每页包含多少个Item。 |
范例:AsyncTask。
private final class MyAsyncTask extends AsyncTask<Object, Object, Object>{ private View footView; protected void onPreExecute() { // 下载之前先向ListView中添加一个表尾。 footView = inflater.inflate(R.layout.list_foot, null); listView.addFooterView(footView); } protected Object doInBackground(Object... params) { IPersonDAO dao = new PersonDAOImpl(getApplicationContext()); List<Person> list = dao.findAll(currentPage, pageSize); if(list.size()>0){ myAdapter.setPersons(list); } this.publishProgress(list.size()>0); return null; } protected void onProgressUpdate(Object... values) { // 下载之后将表尾删除。 listView.removeFooterView(footView); if((Boolean)values[0]){ // 只有成功获取了数据之后,才会通知ListViw更新。 myAdapter.notifyDataSetChanged(); }else{ Toast.makeText(Main.this,"数据加载完成",Toast.long()); } } |