package com.example.swiperefreshlayout;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends Activity {
private SwipeRefreshLayout sr;
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);
sr = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
ListView list = (ListView) findViewById(R.id.listView);
// 设置刷新动画的颜色,可以设置1或者更多.
// 我们暂时使用三个Android系统自带的颜色。
sr.setColorSchemeResources(android.R.color.holo_blue_dark,
android.R.color.holo_green_dark,
android.R.color.holo_orange_dark);
sr.setOnRefreshListener(new OnRefreshListener() {
// SwipeRefreshLayout接管其包裹的ListView下拉事件。
@Override
public void onRefresh() {
// 每一次对ListView的下拉动作,将触发SwipeRefreshLayout的onRefresh()。
longTimeOperation();
}
});
// 使用Android系统自带的一个简单TextView布局文件android.R.layout.simple_list_item_1显示我们的额数据内容。
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, data);
list.setAdapter(adapter);
}
// 每一次下拉刷新将触发更新操作动作。
// 这里将是比较耗时的操作:如网络请求的数据,加载一个大图片。
// 简单期间,我们假设就是简单的将count数据加1,然后更新显示。
// 备注:sr.setRefreshing(true) 到 sr.setRefreshing(false)之间的这段代码 ,
// 在实际的应用开发中一般就是线程化的、耗时的或者后台的操作代码。
private void longTimeOperation() {
// true,刷新开始,所以启动刷新的UI样式
sr.setRefreshing(true);
// 开始启动刷新
// 在这里放耗时操作的 AsyncTask线程、后台Service等代码
// add(0,xxx)每次更新的数据添加到头部
data.add(0, "" + count++);
adapter.notifyDataSetChanged();
// 刷新完毕
// false,刷新完成,要停止UI的刷新表现样式
sr.setRefreshing(false);
}
}
<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"
tools:context="com.example.swiperefreshlayout.MainActivity" >
<android.support.v4.widget.SwipeRefreshLayout
android:id="@+id/swipeRefreshLayout"
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"
>
</ListView>
</android.support.v4.widget.SwipeRefreshLayout>
</LinearLayout>