读书人

Listview中运用线程实现无限加载更多项

发布时间: 2012-09-27 11:11:17 作者: rapoo

Listview中使用线程实现无限加载更多项目的功能
在现在的SINA微博或者象twitter,dzone等网站中,当加载一个很长的列表时,往往都是
先加载部分内容,然后当用户用拖拉条往下拖动时,再加载更多的内容.这里在android
中,可以用listview搭配线程实现同样的功能,举例如下:

1)首先设置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方法如下:



在这个线程里,实际上就是用循环往listview中加日期,产生从当天时间起的若干个日期格式,然后调用 runOnUiThread(returnRes);去更新UI主线程,注意 runOnUiThread是
android提供的方法,可以帮助你在线程中执行UI更新操作.

 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,因为已经加载完了一次了.

读书人网 >移动开发

热点推荐