Android官方的下拉刷新SwipeRefreshLayout更新圆圈不动的小改进和解决
之前我写了一篇文章介绍了Android官方的下拉刷新组件SwipeRefreshLayout,《Android SwipeRefreshLayout:谷歌官方SDK包中的下拉刷新(文章链接地址:http://blog.csdn.net/zhangphil/article/details/46965377 )》,发现存在一些问题,问题在下拉刷新时候,上方转动的更新指示圆圈会暂停转动,当时写文章时候因为添加数据很快就返回,最近在处理长时间数据操作时候这个问题暴露出来了,对此进行改进,其实就是用AsyncTask做后台数据的好事操作,然后更新。
完善后的代码:
测试代码:
package zhangphil.materialdesign;
import java.util.ArrayList;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.widget.ArrayAdapter;
import android.widget.ListView;
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.swipeRefreshLayout);
swipeRefreshLayout.setSize(SwipeRefreshLayout.LARGE);
// 设置下拉多少距离之后开始刷新数据
swipeRefreshLayout.setDistanceToTriggerSync(100);
// 设置进度条背景颜色
swipeRefreshLayout.setProgressBackgroundColorSchemeColor(this.getResources().getColor(android.R.color.holo_blue_light));
// 设置刷新动画的颜色,可以设置1或者更多.
swipeRefreshLayout.setColorSchemeColors(getResources().getColor(android.R.color.holo_blue_bright),
getResources().getColor(android.R.color.holo_orange_light),
getResources().getColor(android.R.color.holo_green_light));
swipeRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
@Override
public void onRefresh() {
/**
* 注意:AsyncTask是单线程顺序执行的线程任务。
* 如果涉及到大量、耗时的线程加载任务,可以考虑自己利用Thread(ExecutorService线程池)+Handler+Message实现。
* */
LongTimeOperationTask task = new LongTimeOperationTask();
task.execute();
}
});
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data);
ListView listView = (ListView) findViewById(android.R.id.list);
listView.setAdapter(adapter);
}
private class LongTimeOperationTask extends AsyncTask<String, Integer, String> {
@Override
protected void onPreExecute() {
swipeRefreshLayout.setRefreshing(true);
}
@Override
protected String doInBackground(String... params) {
SystemClock.sleep(3000);
data.add(0, "数据" + (count++));
return null;
}
@Override
protected void onPostExecute(String result) {
adapter.notifyDataSetChanged();
swipeRefreshLayout.setRefreshing(false);
}
}
}
布局文件:
<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/swipeRefreshLayout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ListView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</android.support.v4.widget.SwipeRefreshLayout>
效果: