- 这里我们将采取的方案是使用组合View的方式,先自定义一个布局继承自LinearLayout,然后在这个布局中加入下拉头和ListView这两个子元素,并让这两个子元素纵向排列。初始化的时候,让下拉头向上偏移出屏幕,这样我们看到的就只有ListView了。然后对ListView的touch事件进行监听,如果当前ListView已经滚动到顶部并且手指还在向下拉的话,那就将下拉头显示出来,松手后进行刷新操作,并将下拉头隐藏。那我们现在就来动手实现一下,新建一个项目起名叫PullToRefreshTest,先在项目中定义一个下拉头的布局文件pull_to_refresh.xml,代码如下所示:
1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
2 xmlns:tools="http://schemas.android.com/tools"
3 android:id="@+id/pull_to_refresh_head"
4 android:layout_width="fill_parent"
5 android:layout_height="60dip" >
6 <LinearLayout
7 android:layout_width="200dip"
8 android:layout_height="60dip"
9 android:layout_centerInParent="true"
10 android:orientation="horizontal" >
11 <RelativeLayout
12 android:layout_width="0dip"
13 android:layout_height="60dip"
14 android:layout_weight="3"
15 >
16 <ImageView
17 android:id="@+id/arrow"
18 android:layout_width="wrap_content"
19 android:layout_height="wrap_content"
20 android:layout_centerInParent="true"
21 android:src="@drawable/arrow"
22 />
23 <ProgressBar
24 android:id="@+id/progress_bar"
25 android:layout_width="30dip"
26 android:layout_height="30dip"
27 android:layout_centerInParent="true"
28 android:visibility="gone"
29 />
30 </RelativeLayout>
31 <LinearLayout
32 android:layout_width="0dip"
33 android:layout_height="60dip"
34 android:layout_weight="12"
35 android:orientation="vertical" >
36 <TextView
37 android:id="@+id/description"
38 android:layout_width="fill_parent"
39 android:layout_height="0dip"
40 android:layout_weight="1"
41 android:gravity="center_horizontal|bottom"
42 android:text="@string/pull_to_refresh" />
43 <TextView
44 android:id="@+id/updated_at"
45 android:layout_width="fill_parent"
46 android:layout_height="0dip"
47 android:layout_weight="1"
48 android:gravity="center_horizontal|top"
49 android:text="@string/updated_at" />
50 </LinearLayout>
51 </LinearLayout>
52 </RelativeLayout>
- 在这个布局中,我们包含了一个下拉指示箭头,一个下拉状态文字提示,和一个上次更新的时间。当然,还有一个隐藏的旋转进度条,只有正在刷新的时候我们才会将它显示出来。布局中所有引用的字符串我们都放在strings.xml中,如下所示:
1 <?xml version="1.0" encoding="utf-8"?>
2 <resources>
3 <string name="app_name">PullToRefreshTest</string>
4 <string name="pull_to_refresh">下拉可以刷新</string>
5 <string name="release_to_refresh">释放立即刷新</string>
6 <string name="refreshing">正在刷新…</string>
7 <string name="not_updated_yet">暂未更新过</string>
8 <string name="updated_at">上次更新于%1$s前</string>
9 <string name="updated_just_now">刚刚更新</string>
10 <string name="time_error">时间有问题</string>
11 </resources>
- 然后新建一个RefreshableView继承自LinearLayout,代码如下所示:
1 public class RefreshableView extends LinearLayout implements OnTouchListener {
2 //下拉状态
3 public static final int STATUS_PULL_TO_REFRESH = 0;
4 //释放立即刷新状态
5 public static final int STATUS_RELEASE_TO_REFRESH = 1
6 //正在刷新状态
7 public static final int STATUS_REFRESHING = 2;
8 //刷新完成或未刷新状态
9 public static final int STATUS_REFRESH_FINISHED = 3;
10 //下拉头部回滚的速度
11 public static final int SCROLL_SPEED = -20;
12 //一分钟的毫秒值,用于判断上次的更新时间
13 public static final long ONE_MINUTE = 60 * 1000;
14 //一小时的毫秒值,用于判断上次的更新时间
15 public static final long ONE_HOUR = 60 * ONE_MINUTE;
16 //一天的毫秒值,用于判断上次的更新时间
17 public static final long ONE_DAY = 24 * ONE_HOUR;
18 //一月的毫秒值,用于判断上次的更新时间
19 public static final long ONE_MONTH = 30 * ONE_DAY;
20 //一年的毫秒值,用于判断上次的更新时间
21 public static final long ONE_YEAR = 12 * ONE_MONTH;
22 //上次更新时间的字符串常量,用于作为SharedPreferences的键值
23 private static final String UPDATED_AT = "updated_at";
24 //下拉刷新的回调接口
25 private PullToRefreshListener mListener;
26 //用于存储上次更新时间
27 private SharedPreferences preferences;
28 //下拉头的View
29 private View header;
30 //需要去下拉刷新的ListView
31 private ListView listView;
32 //刷新时显示的进度条
33 private ProgressBar progressBar;
34 //指示下拉和释放的箭头
35 private ImageView arrow;
36 //指示下拉和释放的文字描述
37 private TextView description;
38 //上次更新时间的文字描述
39 private TextView updateAt;
40 //下拉头的布局参数
41 private MarginLayoutParams headerLayoutParams;
42 //上次更新时间的毫秒值
43 private long lastUpdateTime;
44 //为了防止不同界面的下拉刷新在上次更新时间上互相有冲突,使用id来做区分
45 private int mId = -1;
46 //下拉头的高度
47 private int hideHeaderHeight;
48 //当前处理什么状态,可选值有STATUS_PULL_TO_REFRESH,STATUS_RELEASE_TO_REFRESH,STATUS_REFRESHING 和 STATUS_REFRESH_FINISHED
49 private int currentStatus = STATUS_REFRESH_FINISHED;;
50 //记录上一次的状态是什么,避免进行重复操作
51 private int lastStatus = currentStatus;
52 //手指按下时的屏幕纵坐标
53 private float yDown;
54 //在被判定为滚动之前用户手指可以移动的最大值。
55 private int touchSlop;
56 //是否已加载过一次layout,这里onLayout中的初始化只需加载一次
57 private boolean loadOnce;
58 //当前是否可以下拉,只有ListView滚动到头的时候才允许下拉
59 private boolean ableToPull;
60
61 //下拉刷新控件的构造函数,会在运行时动态添加一个下拉头的布局。
62 public RefreshableView(Context context, AttributeSet attrs) {
63 super(context, attrs);
64 preferences = PreferenceManager.getDefaultSharedPreferences(context);
65 header = LayoutInflater.from(context).inflate(R.layout.pull_to_refresh, null, true);
66 progressBar = (ProgressBar) header.findViewById(R.id.progress_bar);
67 arrow = (ImageView) header.findViewById(R.id.arrow);
68 description = (TextView) header.findViewById(R.id.description);
69 updateAt = (TextView) header.findViewById(R.id.updated_at);
70 touchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
71 refreshUpdatedAtValue();
72 setOrientation(VERTICAL);
73 addView(header, 0);
74 }
75
76 //进行一些关键性的初始化操作,比如:将下拉头向上偏移进行隐藏,给ListView注册touch事件。
77 protected void onLayout(boolean changed, int l, int t, int r, int b) {
78 super.onLayout(changed, l, t, r, b);
79 if (changed && !loadOnce) {
80 hideHeaderHeight = -header.getHeight();
81 headerLayoutParams = (MarginLayoutParams) header.getLayoutParams();
82 headerLayoutParams.topMargin = hideHeaderHeight;
83 listView = (ListView) getChildAt(1);
84 listView.setOnTouchListener(this);
85 loadOnce = true;
86 }
87 }
88
89 //当ListView被触摸时调用,其中处理了各种下拉刷新的具体逻辑。
90 public boolean onTouch(View v, MotionEvent event) {
91 setIsAbleToPull(event);
92 if (ableToPull) {
93 switch (event.getAction()) {
94 case MotionEvent.ACTION_DOWN:
95 yDown = event.getRawY();
96 break;
97 case MotionEvent.ACTION_MOVE:
98 float yMove = event.getRawY();
99 int distance = (int) (yMove - yDown);
100
101 // 如果手指是下滑状态,并且下拉头是完全隐藏的,就屏蔽下拉事件
102 if (distance <= 0 && headerLayoutParams.topMargin <= hideHeaderHeight) {
103 return false;
104 }
105 if (distance < touchSlop) {
106 return false;
107 }
108 if (currentStatus != STATUS_REFRESHING) {
109 if (headerLayoutParams.topMargin > 0) {
110 currentStatus = STATUS_RELEASE_TO_REFRESH;
111 } else {
112 currentStatus = STATUS_PULL_TO_REFRESH;
113 }
114
115 // 通过偏移下拉头的topMargin值,来实现下拉效果
116 headerLayoutParams.topMargin = (distance / 2) + hideHeaderHeight;
117 header.setLayoutParams(headerLayoutParams);
118 }
119 break;
120 case MotionEvent.ACTION_UP:
121 default:
122 if (currentStatus == STATUS_RELEASE_TO_REFRESH) {
123
124 // 松手时如果是释放立即刷新状态,就去调用正在刷新的任务
125 new RefreshingTask().execute();
126 } else if (currentStatus == STATUS_PULL_TO_REFRESH) {
127
128 // 松手时如果是下拉状态,就去调用隐藏下拉头的任务
129 new HideHeaderTask().execute();
130 }
131 break;
132 }
133
134 // 时刻记得更新下拉头中的信息
135 if (currentStatus == STATUS_PULL_TO_REFRESH
136 || currentStatus == STATUS_RELEASE_TO_REFRESH) {
137 updateHeaderView();
138
139 // 当前正处于下拉或释放状态,要让ListView失去焦点,否则被点击的那一项会一直处于选中状态
140 listView.setPressed(false);
141 listView.setFocusable(false);
142 listView.setFocusableInTouchMode(false);
143 lastStatus = currentStatus;
144
145 // 当前正处于下拉或释放状态,通过返回true屏蔽掉ListView的滚动事件
146 return true;
147 }
148 }
149 return false;
150 }
151
152 //给下拉刷新控件注册一个监听器。
153
154 //为了防止不同界面的下拉刷新在上次更新时间上互相有冲突, 请不同界面在注册下拉刷新监听器时一定要传入不同的id。
155 public void setOnRefreshListener(PullToRefreshListener listener, int id) {
156 mListener = listener;
157 mId = id;
158 }
159
160 // 当所有的刷新逻辑完成后,记录调用一下,否则你的ListView将一直处于正在刷新状态。
161 public void finishRefreshing() {
162 currentStatus = STATUS_REFRESH_FINISHED;
163 preferences.edit().putLong(UPDATED_AT + mId, System.currentTimeMillis()).commit();
164 new HideHeaderTask().execute();
165 }
166
167 //根据当前ListView的滚动状态来设定 {@link #ableToPull}的值,每次都需要在onTouch中第一个执行,这样可以判断出当前应该是滚动ListView,还是应该进行下拉。
168 private void setIsAbleToPull(MotionEvent event) {
169 View firstChild = listView.getChildAt(0);
170 if (firstChild != null) {
171 int firstVisiblePos = listView.getFirstVisiblePosition();
172 if (firstVisiblePos == 0 && firstChild.getTop() == 0) {
173 if (!ableToPull) {
174 yDown = event.getRawY();
175 }
176
177 // 如果首个元素的上边缘,距离父布局值为0,就说明ListView滚动到了最顶部,此时应该允许下拉刷新
178 ableToPull = true;
179 } else {
180 if (headerLayoutParams.topMargin != hideHeaderHeight) {
181 headerLayoutParams.topMargin = hideHeaderHeight;
182 header.setLayoutParams(headerLayoutParams);
183 }
184 ableToPull = false;
185 }
186 } else {
187
188 // 如果ListView中没有元素,也应该允许下拉刷新
189 ableToPull = true;
190 }
191 }
192
193 //更新下拉头中的信息。
194 private void updateHeaderView() {
195 if (lastStatus != currentStatus) {
196 if (currentStatus == STATUS_PULL_TO_REFRESH) {
197 description.setText(getResources().getString(R.string.pull_to_refresh));
198 arrow.setVisibility(View.VISIBLE);
199 progressBar.setVisibility(View.GONE);
200 rotateArrow();
201 } else if (currentStatus == STATUS_RELEASE_TO_REFRESH) {
202 description.setText(getResources().getString(R.string.release_to_refresh));
203 arrow.setVisibility(View.VISIBLE);
204 progressBar.setVisibility(View.GONE);
205 rotateArrow();
206 } else if (currentStatus == STATUS_REFRESHING) {
207 description.setText(getResources().getString(R.string.refreshing));
208 progressBar.setVisibility(View.VISIBLE);
209 arrow.clearAnimation();
210 arrow.setVisibility(View.GONE);
211 }
212 refreshUpdatedAtValue();
213 }
214 }
215
216 //根据当前的状态来旋转箭头。
217 private void rotateArrow() {
218 float pivotX = arrow.getWidth() / 2f;
219 float pivotY = arrow.getHeight() / 2f;
220 float fromDegrees = 0f;
221 float toDegrees = 0f;
222 if (currentStatus == STATUS_PULL_TO_REFRESH) {
223 fromDegrees = 180f;
224 toDegrees = 360f;
225 } else if (currentStatus == STATUS_RELEASE_TO_REFRESH) {
226 fromDegrees = 0f;
227 toDegrees = 180f;
228 }
229
230 RotateAnimation animation = new RotateAnimation(fromDegrees, toDegrees, pivotX, pivotY);
231 animation.setDuration(100);
232 animation.setFillAfter(true);
233 arrow.startAnimation(animation);
234 }
235
236 //刷新下拉头中上次更新时间的文字描述。
237 private void refreshUpdatedAtValue() {
238 lastUpdateTime = preferences.getLong(UPDATED_AT + mId, -1);
239 long currentTime = System.currentTimeMillis();
240 long timePassed = currentTime - lastUpdateTime;
241 long timeIntoFormat;
242 String updateAtValue;
243 if (lastUpdateTime == -1) {
244 updateAtValue = getResources().getString(R.string.not_updated_yet);
245 } else if (timePassed < 0) {
246 updateAtValue = getResources().getString(R.string.time_error);
247 } else if (timePassed < ONE_MINUTE) {
248 updateAtValue = getResources().getString(R.string.updated_just_now);
249 } else if (timePassed < ONE_HOUR) {
250 timeIntoFormat = timePassed / ONE_MINUTE;
251 String value = timeIntoFormat + "分钟";
252 updateAtValue = String.format(getResources().getString(R.string.updated_at), value);
253 } else if (timePassed < ONE_DAY) {
254 timeIntoFormat = timePassed / ONE_HOUR;
255 String value = timeIntoFormat + "小时";
256 updateAtValue = String.format(getResources().getString(R.string.updated_at), value);
257 } else if (timePassed < ONE_MONTH) {
258 timeIntoFormat = timePassed / ONE_DAY;
259 String value = timeIntoFormat + "天";
260 updateAtValue = String.format(getResources().getString(R.string.updated_at), value);
261 } else if (timePassed < ONE_YEAR) {
262 timeIntoFormat = timePassed / ONE_MONTH;
263 String value = timeIntoFormat + "个月";
264 updateAtValue = String.format(getResources().getString(R.string.updated_at), value);
265 } else {
266 timeIntoFormat = timePassed / ONE_YEAR;
267 String value = timeIntoFormat + "年";
268 updateAtValue = String.format(getResources().getString(R.string.updated_at), value);
269 }
270 updateAt.setText(updateAtValue);
271 }
272
273 //正在刷新的任务,在此任务中会去回调注册进来的下拉刷新监听器。
274 class RefreshingTask extends AsyncTask<Void, Integer, Void> {
275 protected Void doInBackground(Void... params) {
276 int topMargin = headerLayoutParams.topMargin;
277 while (true) {
278 topMargin = topMargin + SCROLL_SPEED;
279 if (topMargin <= 0) {
280 topMargin = 0;
281 break;
282 }
283 publishProgress(topMargin);
284 sleep(10);
285 }
286 currentStatus = STATUS_REFRESHING;
287 publishProgress(0);
288 if (mListener != null) {
289 mListener.onRefresh();
290 }
291 return null;
292 }
293
294 protected void onProgressUpdate(Integer... topMargin) {
295 updateHeaderView();
296 headerLayoutParams.topMargin = topMargin[0];
297 header.setLayoutParams(headerLayoutParams);
298 }
299 }
300
301 //隐藏下拉头的任务,当未进行下拉刷新或下拉刷新完成后,此任务将会使下拉头重新隐藏。
302
303 class HideHeaderTask extends AsyncTask<Void, Integer, Integer> {
304 protected Integer doInBackground(Void... params) {
305 int topMargin = headerLayoutParams.topMargin;
306 while (true) {
307 topMargin = topMargin + SCROLL_SPEED;
308 if (topMargin <= hideHeaderHeight) {
309 topMargin = hideHeaderHeight;
310 break;
311 }
312 publishProgress(topMargin);
313 sleep(10);
314 }
315 return topMargin;
316 }
317
318 protected void onProgressUpdate(Integer... topMargin) {
319 headerLayoutParams.topMargin = topMargin[0];
320 header.setLayoutParams(headerLayoutParams);
321 }
322
323 protected void onPostExecute(Integer topMargin) {
324 headerLayoutParams.topMargin = topMargin;
325 header.setLayoutParams(headerLayoutParams);
326 currentStatus = STATUS_REFRESH_FINISHED;
327 }
328 }
329
330 //使当前线程睡眠指定的毫秒数。指定当前线程睡眠多久,以毫秒为单位
331 private void sleep(int time) {
332 try {
333 Thread.sleep(time);
334 } catch (InterruptedException e) {
335 e.printStackTrace();
336 }
337 }
338
339 //下拉刷新的监听器,使用下拉刷新的地方应该注册此监听器来获取刷新回调。
340 public interface PullToRefreshListener {
341
342 //刷新时会去回调此方法,在方法内编写具体的刷新逻辑。注意此方法是在子线程中调用的, 你可以不必另开线程来进行耗时操作。
343 void onRefresh();
344 }
345 }
- 这个类是整个下拉刷新功能中最重要的一个类,注释已经写得比较详细了,我再简单解释一下。首先在RefreshableView的构造函数中动态添加了刚刚定义的pull_to_refresh这个布局作为下拉头,然后在onLayout方法中将下拉头向上偏移出了屏幕,再给ListView注册了touch事件。之后每当手指在ListView上滑动时,onTouch方法就会执行。在onTouch方法中的第一行就调用了setIsAbleToPull方法来判断ListView是否滚动到了最顶部,只有滚动到了最顶部才会执行后面的代码,否则就视为正常的ListView滚动,不做任何处理。当ListView滚动到了最顶部时,如果手指还在向下拖动,就会改变下拉头的偏移值,让下拉头显示出来,下拉的距离设定为手指移动距离的1/2,这样才会有拉力的感觉。如果下拉的距离足够大,在松手的时候就会执行刷新操作,如果距离不够大,就仅仅重新隐藏下拉头。
- 具体的刷新操作会在RefreshingTask中进行,其中在doInBackground方法中回调了PullToRefreshListener接口的onRefresh方法,这也是大家在使用RefreshableView时必须要去实现的一个接口,因为具体刷新的逻辑就应该写在onRefresh方法中,后面会演示使用的方法。
- 另外每次在下拉的时候都还会调用updateHeaderView方法来改变下拉头中的数据,比如箭头方向的旋转,下拉文字描述的改变等。更加深入的理解请大家仔细去阅读RefreshableView中的代码。
现在我们已经把下拉刷新的所有功能都完成了,接下来就要看一看如何在项目中引入下拉刷新了。打开或新建activity_main.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=".MainActivity" >
6
7 <com.example.pulltorefreshtest.RefreshableView
8 android:id="@+id/refreshable_view"
9 android:layout_width="fill_parent"
10 android:layout_height="fill_parent" >
11
12 <ListView
13 android:id="@+id/list_view"
14 android:layout_width="fill_parent"
15 android:layout_height="fill_parent" >
16 </ListView>
17
18 </com.example.pulltorefreshtest.RefreshableView>
19 </RelativeLayout>
- 可以看到,我们在自定义的RefreshableView中加入了一个ListView,这就意味着给这个ListView加入了下拉刷新的功能,就是这么简单!然后我们再来看一下程序的主Activity,打开或新建MainActivity,加入如下代码:
1 public class MainActivity extends Activity {
2 RefreshableView refreshableView;
3 ListView listView;
4 ArrayAdapter<String> adapter;
5 String[] items = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L" };
6
7 protected void onCreate(Bundle savedInstanceState) {
8 super.onCreate(savedInstanceState);
9 requestWindowFeature(Window.FEATURE_NO_TITLE);
10 setContentView(R.layout.activity_main);
11 refreshableView = (RefreshableView) findViewById(R.id.refreshable_view);
12 listView = (ListView) findViewById(R.id.list_view);
13 adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
14 listView.setAdapter(adapter);
15 refreshableView.setOnRefreshListener(new PullToRefreshListener() {
16
17 public void onRefresh() {
18 try {
19 Thread.sleep(3000);
20 } catch (InterruptedException e) {
21 e.printStackTrace();
22 }
23 refreshableView.finishRefreshing();
24 }
25 }, 0);
26 }
27 }
- 可以看到,我们通过调用RefreshableView的setOnRefreshListener方法注册了一个监听器,当ListView正在刷新时就会回调监听器的onRefresh方法,刷新的具体逻辑就在这里处理。而且这个方法已经自动开启了线程,可以直接在onRefresh方法中进行耗时操作,比如向服务器请求最新数据等,在这里我就简单让线程睡眠3秒钟。另外在onRefresh方法的最后,一定要调用RefreshableView中的finishRefreshing方法,这个方法是用来通知RefreshableView刷新结束了,不然我们的ListView将一直处于正在刷新的状态。
- 不知道大家有没有注意到,setOnRefreshListener这个方法其实是有两个参数的,我们刚刚也是传入了一个不起眼的0。那这第二个参数是用来做什么的呢?由于RefreshableView比较智能,它会自动帮我们记录上次刷新完成的时间,然后下拉的时候会在下拉头中显示距上次刷新已过了多久。这是一个非常好用的功能,让我们不用再自己手动去记录和计算时间了,但是却存在一个问题。
- 如果当前我们的项目中有三个地方都使用到了下拉刷新的功能,现在在一处进行了刷新,其它两处的时间也都会跟着改变!因为刷新完成的时间是记录在配置文件中的,由于在一处刷新更改了配置文件,导致在其它两处读取到的配置文件时间已经是更改过的了。
- 那解决方案是什么?就是每个用到下拉刷新的地方,给setOnRefreshListener方法的第二个参数中传入不同的id就行了。这样各处的上次刷新完成时间都是单独记录的,相互之间就不会再有影响。
- 让我们来运行一下,看看效果吧。
- 效果看起来还是非常不错的。我们最后再来总结一下,在项目中引入ListView下拉刷新功能只需三步:
- 在Activity的布局文件中加入自定义的RefreshableView,并让ListView包含在其中。
- 在Activity中调用RefreshableView的setOnRefreshListener方法注册回调接口。
- 在onRefresh方法的最后,记得调用RefreshableView的finishRefreshing方法,通知刷新结束。