开源库下载地址
https://github.com/chrisbanes/Android-PullToRefresh
解压后导入开源库
效果图
代码
package com.xiaoke.openfreash;
import java.util.ArrayList;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends Activity {
private PullToRefreshListView listview = null;
private ArrayList<String> list = null;
private ArrayAdapter adapter = null;
private int index = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = new ArrayList<String>();
listview = (PullToRefreshListView) findViewById(R.id.pull_id);
// 设置下拉刷新,不是上拉刷新
listview.setMode(Mode.PULL_FROM_START);
// 监听开始
listview.setOnRefreshListener(new OnRefreshListener<ListView>() {
// 下拉执行
@Override
public void onRefresh(PullToRefreshBase<ListView> refreshView) {
// TODO Auto-generated method stub
new MyTask().execute();
}
});
// 执行listview
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1,
list);
listview.setAdapter(adapter);
}
public class MyTask extends AsyncTask {
@Override
protected void onPreExecute() {
// 下拉显示开始
listview.setRefreshing();
}
@Override
protected Object doInBackground(Object... params) {
// 模拟数据增加,模拟耗时操作
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return index++;
}
@Override
protected void onPostExecute(Object result) {
// 添加数据
list.add(0, "数据" + result);
// 更新界面
adapter.notifyDataSetChanged();
// 加载完成结束下拉界面
listview.onRefreshComplete();
}
}
}
布局文件:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.xiaoke.openfreash.MainActivity" >
<com.handmark.pulltorefresh.library.PullToRefreshListView
android:id="@+id/pull_id"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</RelativeLayout>