效果如下:
第三方开源框架 PullToRefreshListView 链接:点击打开链接
布局文件:
<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.android.flush.MainActivity" >
<com.handmark.pulltorefresh.library.PullToRefreshListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
package com.android.flush;
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;
import android.widget.TextView;
public class MainActivity extends Activity {
private int count = 0;
private PullToRefreshListView listView;
private ArrayAdapter<String> adapter;
private ArrayList<String> mDatas = new ArrayList<String>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (PullToRefreshListView)findViewById(R.id.listView);
mDatas = new ArrayList<String>();
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mDatas);
// 设置刷新模式
listView.setMode(Mode.PULL_FROM_START);
listView.setOnRefreshListener(new OnRefreshListener<ListView>() {
@Override
public void onRefresh(PullToRefreshBase<ListView> refreshView) {
new MyTask().execute();
}
});
listView.setAdapter(adapter);
// 设置提示信息
TextView textView = new TextView(this);
textView.setText("下拉刷新");
listView.setEmptyView(textView);
}
private class MyTask extends AsyncTask<Integer, Integer, Integer>{
@Override
protected Integer doInBackground(Integer... params) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return count++;
}
@Override
protected void onPreExecute() {
listView.setRefreshing();
}
@Override
protected void onPostExecute(Integer result) {
mDatas.add(0, result++ +"");
listView.setLastUpdatedLabel("更新时间:" + System.currentTimeMillis());
// 通知 adapter 更新,不能少
adapter.notifyDataSetChanged();
listView.onRefreshComplete();
}
}
}