首先设置footer部分,即在listview的下面设置footview,footview的模版如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:gravity="center_horizontal"
android:padding="3dp"
android:layout_height="fill_parent">
<TextView
android:id="@id/android:empty"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center"
android:padding="5dp"
android:text="Loading more days..."/>
</LinearLayout>
然后记得在加到adapter前,把footview加到listview中去
View footerView = ((LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.listfooter, null, false);
this.getListView().addFooterView(footerView);
this.setListAdapter(adapter);
然后,listview的onscroll方法如下:
Java代码:
this.getListView().setOnScrollListener(new OnScrollListener(){
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
int lastInScreen = firstVisibleItem + visibleItemCount;
String last=Integer.toString(lastInScreen);
Log.d("show",last);
String total=Integer.toString(totalItemCount);
Log.d("total",total);
if((lastInScreen == totalItemCount) && !(loadingMore)){
Thread thread = new Thread(null, loadMoreListItems);
thread.start();
}
}
});
Thread thread = new Thread(null, loadMoreListItems);
thread.start();
下面来分析下,其中,可以预先设置一个屏的listview能显示多少条记录,比如设置为5条,这里itemsPerPage=15,然后:
int lastInScreen = firstVisibleItem + visibleItemCount;
这里,获得每屏中最后一条数据的位置,比如一次先显示5条,则lastInScreen=5了。
if((lastInScreen == totalItemCount) && !(loadingMore)){
Thread thread = new Thread(null, loadMoreListItems);
thread.start();
}
这里是判断,如果是滚动了滚动条,并且用户以及功能浏览完了一次屏幕所需要的数目(比如5个),则启用线程序loadMoreListItems去处理,加载另外的新的5个了。
而如果没滚动,则第一次显示时,也要启用线程序loadMoreListItems去处理。下面看loadMoreListItems:
Java代码:
private Runnable loadMoreListItems = new Runnable() {
public void run() {
loadingMore = true;
myListItems = new ArrayList<String>();
//Simulate a delay, delete this on a production environment!
try { Thread.sleep(1000);
} catch (InterruptedException e) {}
//Get 15 new listitems
for (int i = 0; i < itemsPerPage; i++) {
myListItems.add("Date: " + (d.get(Calendar.MONTH)+ 1) + "/" + d.get(Calendar.DATE) + "/" + d.get(Calendar.YEAR) );
d.add(Calendar.DATE, 1);
}
runOnUiThread(returnRes);
}
;
在这个线程里,实际上就是用循环往listview中加日期,产生从当天时间起的若干个日期格式,然后调用runOnUiThread(returnRes);去更新UI主线程,注意 runOnUiThread是android提供的方法,可以帮助你在线程中执行UI更新操作。
Java代码:
private Runnable returnRes = new Runnable() {
public void run() {
if(myListItems != null && myListItems.size() > 0){
for(int i=0;i<myListItems.size();i++)
adapter.add(myListItems.get(i));
}
adapter.notifyDataSetChanged();
loadingMore = false;
}
};
在更新主线程中,十分简单,只不过往adapter中去增加元素,并且notifyDataSetChanged通知listview起变化了,并设置loadingMore=false,因为已经加载完了一次了。