如下的示意图:
SwipeRefreshLayout 可以不用定义外面的 LinearLayout :
<LinearLayout 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:orientation="vertical"
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.swiperefreshlayouttest.MainActivity" >
<!-- 以一个SwipeRefreshLayout包裹ListView,
SwipeRefreshLayout接管ListView的下拉事件,
若ListView被用户触发下拉动作后,
SwipeRefreshLayout启动下拉刷新的UI表现样式,下拉刷新完毕 -->
<android.support.v4.widget.SwipeRefreshLayout
android:id="@+id/swipe"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.v4.widget.SwipeRefreshLayout>
</LinearLayout>
package com.android.swiperefreshlayouttest;
import java.util.ArrayList;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
/**
* 在android-support-v4包中,谷歌增加了SwipeRefreshLayout,
* 该组件提供基础的下拉刷新表现能力和开放出来供开发者调用的基本接口。
* @author scxh
*
*/
public class MainActivity extends Activity {
private SwipeRefreshLayout swipeRefreshLayout;
private int count = 0;
private ArrayList<String> data = new ArrayList<String>();
private ArrayAdapter<String> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
swipeRefreshLayout = (SwipeRefreshLayout)findViewById(R.id.swipe);
ListView listView = (ListView)findViewById(R.id.listView);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data);
swipeRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
@Override
public void onRefresh() {
// doSomething();
new MyTask().execute();
}
});
listView.setAdapter(adapter);
}
/**
* swipeRefreshLayout.setRefreshing(true) 到
* swipeRefreshLayout.setRefreshing(false)之间的这段代码 ,
* @author scxh
*
*/
private class MyTask extends AsyncTask<Integer, Integer, Integer>{
@Override
protected Integer doInBackground(Integer... params) {
// add(0,xxx)每次将更新的数据xxx添加到头部。
data.add(0, count++ +"");
return count;
}
@Override
protected void onPreExecute() {
// true,刷新开始,所以启动刷新的UI样式。
swipeRefreshLayout.setRefreshing(true);
}
@Override
protected void onPostExecute(Integer count) {
Log.d("===========", count + "");
adapter.notifyDataSetChanged();
swipeRefreshLayout.setRefreshing(false);
}
}
}