《Android SwipeRefreshLayout:谷歌官方SDK包中的下拉刷新》
下拉刷新在如今移动开发中应用如此广泛和普遍,以至于谷歌干脆在SDK中给予支持。在android-support-v4包中,谷歌增加了SwipeRefreshLayout,该组件提供基础的下拉刷新表现能力和开放出来供开发者调用的基本接口。
1 package com.lixu.SwipeRefreshLayoutyongfa; 2 3 import java.util.ArrayList; 4 import android.app.Activity; 5 import android.os.AsyncTask; 6 import android.os.Bundle; 7 import android.support.v4.widget.SwipeRefreshLayout; 8 import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener; 9 import android.widget.ArrayAdapter; 10 import android.widget.ListView; 11 12 public class MainActivity extends Activity { 13 private ArrayAdapter<String> adapter; 14 private ArrayList<String> date; 15 private SwipeRefreshLayout srl; 16 private int count = 0; 17 18 @Override 19 protected void onCreate(Bundle savedInstanceState) { 20 super.onCreate(savedInstanceState); 21 setContentView(R.layout.activity_main); 22 23 date = new ArrayList<String>(); 24 25 ListView lv = (ListView) findViewById(R.id.lv); 26 27 srl = (SwipeRefreshLayout) findViewById(R.id.srl); 28 // 设置刷新动画的颜色. 29 srl.setColorSchemeResources(android.R.color.holo_green_light, android.R.color.holo_blue_bright, 30 android.R.color.holo_red_light); 31 32 srl.setOnRefreshListener(new OnRefreshListener() { 33 // SwipeRefreshLayout接管其包裹的ListView下拉事件。 34 // 每一次对ListView的下拉动作,将触发SwipeRefreshLayout的onRefresh()。 35 @SuppressWarnings("unchecked") 36 @Override 37 public void onRefresh() { 38 39 new MyAsyncTask().execute(); 40 41 } 42 }); 43 adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, date); 44 45 lv.setAdapter(adapter); 46 } 47 48 private class MyAsyncTask extends AsyncTask { 49 @Override 50 protected void onPreExecute() { 51 super.onPreExecute(); 52 // 刷新开始 53 srl.setRefreshing(true); 54 } 55 56 @Override 57 protected Object doInBackground(Object... params) { 58 // 处理一些耗时的事件 59 return count++; 60 } 61 62 @Override 63 protected void onPostExecute(Object result) { 64 super.onPostExecute(result); 65 // add(0,xxx)每次将更新的数据xxx添加到头部。 66 date.add(0, "" + result); 67 // 刷新适配器 68 adapter.notifyDataSetChanged(); 69 // 刷新完毕 70 srl.setRefreshing(false); 71 } 72 73 } 74 75 }
xml文件:
1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 xmlns:tools="http://schemas.android.com/tools" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 tools:context="com.lixu.SwipeRefreshLayoutyongfa.MainActivity" > 6 7 <android.support.v4.widget.SwipeRefreshLayout 8 android:id="@+id/srl" 9 android:layout_width="match_parent" 10 android:layout_height="match_parent" > 11 12 <ListView 13 android:id="@+id/lv" 14 android:layout_width="match_parent" 15 android:layout_height="match_parent" /> 16 </android.support.v4.widget.SwipeRefreshLayout> 17 18 </RelativeLayout>
运行效果: