最近項目中須要用到ListView下拉刷新的功能,一開始想圖省事,在網上直接找一個現成的,但是嘗試了網上多個版本的下拉刷新以後發現效果都不怎麼理想。有些是由於功能不完整或有Bug,有些是由於使用起來太複雜,十全十美的還真沒找到。所以我也是放棄了在網上找現成代碼的想法,本身花功夫編寫了一種很是簡單的下拉刷新實現方案,如今拿出來和你們分享一下。相信在閱讀完本篇文章以後,你們均可以在本身的項目中一分鐘引入下拉刷新功能。html
首先講一下實現原理。這裏咱們將採起的方案是使用組合View的方式,先自定義一個佈局繼承自LinearLayout,而後在這個佈局中加入下拉頭和ListView這兩個子元素,並讓這兩個子元素縱向排列。初始化的時候,讓下拉頭向上偏移出屏幕,這樣咱們看到的就只有ListView了。而後對ListView的touch事件進行監聽,若是當前ListView已經滾動到頂部而且手指還在向下拉的話,那就將下拉頭顯示出來,鬆手後進行刷新操做,並將下拉頭隱藏。原理示意圖以下:java
![](http://static.javashuo.com/static/loading.gif)
那咱們如今就來動手實現一下,新建一個項目起名叫PullToRefreshTest,先在項目中定義一個下拉頭的佈局文件pull_to_refresh.xml,代碼以下所示:android
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:id="@+id/pull_to_refresh_head"
- android:layout_width="fill_parent"
- android:layout_height="60dip" >
-
- <LinearLayout
- android:layout_width="200dip"
- android:layout_height="60dip"
- android:layout_centerInParent="true"
- android:orientation="horizontal" >
-
- <RelativeLayout
- android:layout_width="0dip"
- android:layout_height="60dip"
- android:layout_weight="3"
- >
- <ImageView
- android:id="@+id/arrow"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_centerInParent="true"
- android:src="@drawable/arrow"
- />
- <ProgressBar
- android:id="@+id/progress_bar"
- android:layout_width="30dip"
- android:layout_height="30dip"
- android:layout_centerInParent="true"
- android:visibility="gone"
- />
- </RelativeLayout>
-
- <LinearLayout
- android:layout_width="0dip"
- android:layout_height="60dip"
- android:layout_weight="12"
- android:orientation="vertical" >
-
- <TextView
- android:id="@+id/description"
- android:layout_width="fill_parent"
- android:layout_height="0dip"
- android:layout_weight="1"
- android:gravity="center_horizontal|bottom"
- android:text="@string/pull_to_refresh" />
-
- <TextView
- android:id="@+id/updated_at"
- android:layout_width="fill_parent"
- android:layout_height="0dip"
- android:layout_weight="1"
- android:gravity="center_horizontal|top"
- android:text="@string/updated_at" />
- </LinearLayout>
- </LinearLayout>
-
- </RelativeLayout>
- <span style="font-size:14px;"><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:id="@+id/pull_to_refresh_head"
- android:layout_width="fill_parent"
- android:layout_height="60dip" >
-
- <LinearLayout
- android:layout_width="200dip"
- android:layout_height="60dip"
- android:layout_centerInParent="true"
- android:orientation="horizontal" >
-
- <RelativeLayout
- android:layout_width="0dip"
- android:layout_height="60dip"
- android:layout_weight="3"
- >
- <ImageView
- android:id="@+id/arrow"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_centerInParent="true"
- android:src="@drawable/arrow"
- />
- <ProgressBar
- android:id="@+id/progress_bar"
- android:layout_width="30dip"
- android:layout_height="30dip"
- android:layout_centerInParent="true"
- android:visibility="gone"
- />
- </RelativeLayout>
-
- <LinearLayout
- android:layout_width="0dip"
- android:layout_height="60dip"
- android:layout_weight="12"
- android:orientation="vertical" >
-
- <TextView
- android:id="@+id/description"
- android:layout_width="fill_parent"
- android:layout_height="0dip"
- android:layout_weight="1"
- android:gravity="center_horizontal|bottom"
- android:text="@string/pull_to_refresh" />
-
- <TextView
- android:id="@+id/updated_at"
- android:layout_width="fill_parent"
- android:layout_height="0dip"
- android:layout_weight="1"
- android:gravity="center_horizontal|top"
- android:text="@string/updated_at" />
- </LinearLayout>
- </LinearLayout>
-
- </RelativeLayout></span>
在這個佈局中,咱們包含了一個下拉指示箭頭,一個下拉狀態文字提示,和一個上次更新的時間。固然,還有一個隱藏的旋轉進度條,只有正在刷新的時候咱們纔會將它顯示出來。
佈局中全部引用的字符串咱們都放在strings.xml中,以下所示:服務器
- <?xml version="1.0" encoding="utf-8"?>
- <resources>
-
- <string name="app_name">PullToRefreshTest</string>
- <string name="pull_to_refresh">下拉能夠刷新</string>
- <string name="release_to_refresh">釋放當即刷新</string>
- <string name="refreshing">正在刷新…</string>
- <string name="not_updated_yet">暫未更新過</string>
- <string name="updated_at">上次更新於%1$s前</string>
- <string name="updated_just_now">剛剛更新</string>
- <string name="time_error">時間有問題</string>
-
- </resources>
- <span style="font-size:14px;"><?xml version="1.0" encoding="utf-8"?>
- <resources>
-
- <string name="app_name">PullToRefreshTest</string>
- <string name="pull_to_refresh">下拉能夠刷新</string>
- <string name="release_to_refresh">釋放當即刷新</string>
- <string name="refreshing">正在刷新…</string>
- <string name="not_updated_yet">暫未更新過</string>
- <string name="updated_at">上次更新於%1$s前</string>
- <string name="updated_just_now">剛剛更新</string>
- <string name="time_error">時間有問題</string>
-
- </resources></span>
而後新建一個RefreshableView繼承自LinearLayout,代碼以下所示:app
- public class RefreshableView extends LinearLayout implements OnTouchListener {
-
-
- public static final int STATUS_PULL_TO_REFRESH = 0;
-
-
- public static final int STATUS_RELEASE_TO_REFRESH = 1;
-
-
- public static final int STATUS_REFRESHING = 2;
-
-
- public static final int STATUS_REFRESH_FINISHED = 3;
-
-
- public static final int SCROLL_SPEED = -20;
-
-
- public static final long ONE_MINUTE = 60 * 1000;
-
-
- public static final long ONE_HOUR = 60 * ONE_MINUTE;
-
-
- public static final long ONE_DAY = 24 * ONE_HOUR;
-
-
- public static final long ONE_MONTH = 30 * ONE_DAY;
-
-
- public static final long ONE_YEAR = 12 * ONE_MONTH;
-
-
- private static final String UPDATED_AT = "updated_at";
-
-
- private PullToRefreshListener mListener;
-
-
- private SharedPreferences preferences;
-
-
- private View header;
-
-
- private ListView listView;
-
-
- private ProgressBar progressBar;
-
-
- private ImageView arrow;
-
-
- private TextView description;
-
-
- private TextView updateAt;
-
-
- private MarginLayoutParams headerLayoutParams;
-
-
- private long lastUpdateTime;
-
-
- private int mId = -1;
-
-
- private int hideHeaderHeight;
-
-
- private int currentStatus = STATUS_REFRESH_FINISHED;;
-
-
- private int lastStatus = currentStatus;
-
-
- private float yDown;
-
-
- private int touchSlop;
-
-
- private boolean loadOnce;
-
-
- private boolean ableToPull;
-
-
- public RefreshableView(Context context, AttributeSet attrs) {
- super(context, attrs);
- preferences = PreferenceManager.getDefaultSharedPreferences(context);
- header = LayoutInflater.from(context).inflate(R.layout.pull_to_refresh, null, true);
- progressBar = (ProgressBar) header.findViewById(R.id.progress_bar);
- arrow = (ImageView) header.findViewById(R.id.arrow);
- description = (TextView) header.findViewById(R.id.description);
- updateAt = (TextView) header.findViewById(R.id.updated_at);
- touchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
- refreshUpdatedAtValue();
- setOrientation(VERTICAL);
- addView(header, 0);
- }
-
-
- @Override
- protected void onLayout(boolean changed, int l, int t, int r, int b) {
- super.onLayout(changed, l, t, r, b);
- if (changed && !loadOnce) {
- hideHeaderHeight = -header.getHeight();
- headerLayoutParams = (MarginLayoutParams) header.getLayoutParams();
- headerLayoutParams.topMargin = hideHeaderHeight;
- listView = (ListView) getChildAt(1);
- listView.setOnTouchListener(this);
- loadOnce = true;
- }
- }
-
-
- @Override
- public boolean onTouch(View v, MotionEvent event) {
- setIsAbleToPull(event);
- if (ableToPull) {
- switch (event.getAction()) {
- case MotionEvent.ACTION_DOWN:
- yDown = event.getRawY();
- break;
- case MotionEvent.ACTION_MOVE:
- float yMove = event.getRawY();
- int distance = (int) (yMove - yDown);
-
- if (distance <= 0 && headerLayoutParams.topMargin <= hideHeaderHeight) {
- return false;
- }
- if (distance < touchSlop) {
- return false;
- }
- if (currentStatus != STATUS_REFRESHING) {
- if (headerLayoutParams.topMargin > 0) {
- currentStatus = STATUS_RELEASE_TO_REFRESH;
- } else {
- currentStatus = STATUS_PULL_TO_REFRESH;
- }
-
- headerLayoutParams.topMargin = (distance / 2) + hideHeaderHeight;
- header.setLayoutParams(headerLayoutParams);
- }
- break;
- case MotionEvent.ACTION_UP:
- default:
- if (currentStatus == STATUS_RELEASE_TO_REFRESH) {
-
- new RefreshingTask().execute();
- } else if (currentStatus == STATUS_PULL_TO_REFRESH) {
-
- new HideHeaderTask().execute();
- }
- break;
- }
-
- if (currentStatus == STATUS_PULL_TO_REFRESH
- || currentStatus == STATUS_RELEASE_TO_REFRESH) {
- updateHeaderView();
-
- listView.setPressed(false);
- listView.setFocusable(false);
- listView.setFocusableInTouchMode(false);
- lastStatus = currentStatus;
-
- return true;
- }
- }
- return false;
- }
-
-
- public void setOnRefreshListener(PullToRefreshListener listener, int id) {
- mListener = listener;
- mId = id;
- }
-
-
- public void finishRefreshing() {
- currentStatus = STATUS_REFRESH_FINISHED;
- preferences.edit().putLong(UPDATED_AT + mId, System.currentTimeMillis()).commit();
- new HideHeaderTask().execute();
- }
-
-
- private void setIsAbleToPull(MotionEvent event) {
- View firstChild = listView.getChildAt(0);
- if (firstChild != null) {
- int firstVisiblePos = listView.getFirstVisiblePosition();
- if (firstVisiblePos == 0 && firstChild.getTop() == 0) {
- if (!ableToPull) {
- yDown = event.getRawY();
- }
-
- ableToPull = true;
- } else {
- if (headerLayoutParams.topMargin != hideHeaderHeight) {
- headerLayoutParams.topMargin = hideHeaderHeight;
- header.setLayoutParams(headerLayoutParams);
- }
- ableToPull = false;
- }
- } else {
-
- ableToPull = true;
- }
- }
-
-
- private void updateHeaderView() {
- if (lastStatus != currentStatus) {
- if (currentStatus == STATUS_PULL_TO_REFRESH) {
- description.setText(getResources().getString(R.string.pull_to_refresh));
- arrow.setVisibility(View.VISIBLE);
- progressBar.setVisibility(View.GONE);
- rotateArrow();
- } else if (currentStatus == STATUS_RELEASE_TO_REFRESH) {
- description.setText(getResources().getString(R.string.release_to_refresh));
- arrow.setVisibility(View.VISIBLE);
- progressBar.setVisibility(View.GONE);
- rotateArrow();
- } else if (currentStatus == STATUS_REFRESHING) {
- description.setText(getResources().getString(R.string.refreshing));
- progressBar.setVisibility(View.VISIBLE);
- arrow.clearAnimation();
- arrow.setVisibility(View.GONE);
- }
- refreshUpdatedAtValue();
- }
- }
-
-
- private void rotateArrow() {
- float pivotX = arrow.getWidth() / 2f;
- float pivotY = arrow.getHeight() / 2f;
- float fromDegrees = 0f;
- float toDegrees = 0f;
- if (currentStatus == STATUS_PULL_TO_REFRESH) {
- fromDegrees = 180f;
- toDegrees = 360f;
- } else if (currentStatus == STATUS_RELEASE_TO_REFRESH) {
- fromDegrees = 0f;
- toDegrees = 180f;
- }
- RotateAnimation animation = new RotateAnimation(fromDegrees, toDegrees, pivotX, pivotY);
- animation.setDuration(100);
- animation.setFillAfter(true);
- arrow.startAnimation(animation);
- }
-
-
- private void refreshUpdatedAtValue() {
- lastUpdateTime = preferences.getLong(UPDATED_AT + mId, -1);
- long currentTime = System.currentTimeMillis();
- long timePassed = currentTime - lastUpdateTime;
- long timeIntoFormat;
- String updateAtValue;
- if (lastUpdateTime == -1) {
- updateAtValue = getResources().getString(R.string.not_updated_yet);
- } else if (timePassed < 0) {
- updateAtValue = getResources().getString(R.string.time_error);
- } else if (timePassed < ONE_MINUTE) {
- updateAtValue = getResources().getString(R.string.updated_just_now);
- } else if (timePassed < ONE_HOUR) {
- timeIntoFormat = timePassed / ONE_MINUTE;
- String value = timeIntoFormat + "分鐘";
- updateAtValue = String.format(getResources().getString(R.string.updated_at), value);
- } else if (timePassed < ONE_DAY) {
- timeIntoFormat = timePassed / ONE_HOUR;
- String value = timeIntoFormat + "小時";
- updateAtValue = String.format(getResources().getString(R.string.updated_at), value);
- } else if (timePassed < ONE_MONTH) {
- timeIntoFormat = timePassed / ONE_DAY;
- String value = timeIntoFormat + "天";
- updateAtValue = String.format(getResources().getString(R.string.updated_at), value);
- } else if (timePassed < ONE_YEAR) {
- timeIntoFormat = timePassed / ONE_MONTH;
- String value = timeIntoFormat + "個月";
- updateAtValue = String.format(getResources().getString(R.string.updated_at), value);
- } else {
- timeIntoFormat = timePassed / ONE_YEAR;
- String value = timeIntoFormat + "年";
- updateAtValue = String.format(getResources().getString(R.string.updated_at), value);
- }
- updateAt.setText(updateAtValue);
- }
-
-
- class RefreshingTask extends AsyncTask<Void, Integer, Void> {
-
- @Override
- protected Void doInBackground(Void... params) {
- int topMargin = headerLayoutParams.topMargin;
- while (true) {
- topMargin = topMargin + SCROLL_SPEED;
- if (topMargin <= 0) {
- topMargin = 0;
- break;
- }
- publishProgress(topMargin);
- sleep(10);
- }
- currentStatus = STATUS_REFRESHING;
- publishProgress(0);
- if (mListener != null) {
- mListener.onRefresh();
- }
- return null;
- }
-
- @Override
- protected void onProgressUpdate(Integer... topMargin) {
- updateHeaderView();
- headerLayoutParams.topMargin = topMargin[0];
- header.setLayoutParams(headerLayoutParams);
- }
-
- }
-
-
- class HideHeaderTask extends AsyncTask<Void, Integer, Integer> {
-
- @Override
- protected Integer doInBackground(Void... params) {
- int topMargin = headerLayoutParams.topMargin;
- while (true) {
- topMargin = topMargin + SCROLL_SPEED;
- if (topMargin <= hideHeaderHeight) {
- topMargin = hideHeaderHeight;
- break;
- }
- publishProgress(topMargin);
- sleep(10);
- }
- return topMargin;
- }
-
- @Override
- protected void onProgressUpdate(Integer... topMargin) {
- headerLayoutParams.topMargin = topMargin[0];
- header.setLayoutParams(headerLayoutParams);
- }
-
- @Override
- protected void onPostExecute(Integer topMargin) {
- headerLayoutParams.topMargin = topMargin;
- header.setLayoutParams(headerLayoutParams);
- currentStatus = STATUS_REFRESH_FINISHED;
- }
- }
-
-
- private void sleep(int time) {
- try {
- Thread.sleep(time);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
-
-
- public interface PullToRefreshListener {
-
-
- void onRefresh();
-
- }
-
- }
- <span style="font-size:14px;">public class RefreshableView extends LinearLayout implements OnTouchListener {
-
-
- public static final int STATUS_PULL_TO_REFRESH = 0;
-
-
- public static final int STATUS_RELEASE_TO_REFRESH = 1;
-
-
- public static final int STATUS_REFRESHING = 2;
-
-
- public static final int STATUS_REFRESH_FINISHED = 3;
-
-
- public static final int SCROLL_SPEED = -20;
-
-
- public static final long ONE_MINUTE = 60 * 1000;
-
-
- public static final long ONE_HOUR = 60 * ONE_MINUTE;
-
-
- public static final long ONE_DAY = 24 * ONE_HOUR;
-
-
- public static final long ONE_MONTH = 30 * ONE_DAY;
-
-
- public static final long ONE_YEAR = 12 * ONE_MONTH;
-
-
- private static final String UPDATED_AT = "updated_at";
-
-
- private PullToRefreshListener mListener;
-
-
- private SharedPreferences preferences;
-
-
- private View header;
-
-
- private ListView listView;
-
-
- private ProgressBar progressBar;
-
-
- private ImageView arrow;
-
-
- private TextView description;
-
-
- private TextView updateAt;
-
-
- private MarginLayoutParams headerLayoutParams;
-
-
- private long lastUpdateTime;
-
-
- private int mId = -1;
-
-
- private int hideHeaderHeight;
-
-
- private int currentStatus = STATUS_REFRESH_FINISHED;;
-
-
- private int lastStatus = currentStatus;
-
-
- private float yDown;
-
-
- private int touchSlop;
-
-
- private boolean loadOnce;
-
-
- private boolean ableToPull;
-
-
- public RefreshableView(Context context, AttributeSet attrs) {
- super(context, attrs);
- preferences = PreferenceManager.getDefaultSharedPreferences(context);
- header = LayoutInflater.from(context).inflate(R.layout.pull_to_refresh, null, true);
- progressBar = (ProgressBar) header.findViewById(R.id.progress_bar);
- arrow = (ImageView) header.findViewById(R.id.arrow);
- description = (TextView) header.findViewById(R.id.description);
- updateAt = (TextView) header.findViewById(R.id.updated_at);
- touchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
- refreshUpdatedAtValue();
- setOrientation(VERTICAL);
- addView(header, 0);
- }
-
-
- @Override
- protected void onLayout(boolean changed, int l, int t, int r, int b) {
- super.onLayout(changed, l, t, r, b);
- if (changed && !loadOnce) {
- hideHeaderHeight = -header.getHeight();
- headerLayoutParams = (MarginLayoutParams) header.getLayoutParams();
- headerLayoutParams.topMargin = hideHeaderHeight;
- listView = (ListView) getChildAt(1);
- listView.setOnTouchListener(this);
- loadOnce = true;
- }
- }
-
-
- @Override
- public boolean onTouch(View v, MotionEvent event) {
- setIsAbleToPull(event);
- if (ableToPull) {
- switch (event.getAction()) {
- case MotionEvent.ACTION_DOWN:
- yDown = event.getRawY();
- break;
- case MotionEvent.ACTION_MOVE:
- float yMove = event.getRawY();
- int distance = (int) (yMove - yDown);
-
- if (distance <= 0 && headerLayoutParams.topMargin <= hideHeaderHeight) {
- return false;
- }
- if (distance < touchSlop) {
- return false;
- }
- if (currentStatus != STATUS_REFRESHING) {
- if (headerLayoutParams.topMargin > 0) {
- currentStatus = STATUS_RELEASE_TO_REFRESH;
- } else {
- currentStatus = STATUS_PULL_TO_REFRESH;
- }
-
- headerLayoutParams.topMargin = (distance / 2) + hideHeaderHeight;
- header.setLayoutParams(headerLayoutParams);
- }
- break;
- case MotionEvent.ACTION_UP:
- default:
- if (currentStatus == STATUS_RELEASE_TO_REFRESH) {
-
- new RefreshingTask().execute();
- } else if (currentStatus == STATUS_PULL_TO_REFRESH) {
-
- new HideHeaderTask().execute();
- }
- break;
- }
-
- if (currentStatus == STATUS_PULL_TO_REFRESH
- || currentStatus == STATUS_RELEASE_TO_REFRESH) {
- updateHeaderView();
-
- listView.setPressed(false);
- listView.setFocusable(false);
- listView.setFocusableInTouchMode(false);
- lastStatus = currentStatus;
-
- return true;
- }
- }
- return false;
- }
-
-
- public void setOnRefreshListener(PullToRefreshListener listener, int id) {
- mListener = listener;
- mId = id;
- }
-
-
- public void finishRefreshing() {
- currentStatus = STATUS_REFRESH_FINISHED;
- preferences.edit().putLong(UPDATED_AT + mId, System.currentTimeMillis()).commit();
- new HideHeaderTask().execute();
- }
-
-
- private void setIsAbleToPull(MotionEvent event) {
- View firstChild = listView.getChildAt(0);
- if (firstChild != null) {
- int firstVisiblePos = listView.getFirstVisiblePosition();
- if (firstVisiblePos == 0 && firstChild.getTop() == 0) {
- if (!ableToPull) {
- yDown = event.getRawY();
- }
-
- ableToPull = true;
- } else {
- if (headerLayoutParams.topMargin != hideHeaderHeight) {
- headerLayoutParams.topMargin = hideHeaderHeight;
- header.setLayoutParams(headerLayoutParams);
- }
- ableToPull = false;
- }
- } else {
-
- ableToPull = true;
- }
- }
-
-
- private void updateHeaderView() {
- if (lastStatus != currentStatus) {
- if (currentStatus == STATUS_PULL_TO_REFRESH) {
- description.setText(getResources().getString(R.string.pull_to_refresh));
- arrow.setVisibility(View.VISIBLE);
- progressBar.setVisibility(View.GONE);
- rotateArrow();
- } else if (currentStatus == STATUS_RELEASE_TO_REFRESH) {
- description.setText(getResources().getString(R.string.release_to_refresh));
- arrow.setVisibility(View.VISIBLE);
- progressBar.setVisibility(View.GONE);
- rotateArrow();
- } else if (currentStatus == STATUS_REFRESHING) {
- description.setText(getResources().getString(R.string.refreshing));
- progressBar.setVisibility(View.VISIBLE);
- arrow.clearAnimation();
- arrow.setVisibility(View.GONE);
- }
- refreshUpdatedAtValue();
- }
- }
-
-
- private void rotateArrow() {
- float pivotX = arrow.getWidth() / 2f;
- float pivotY = arrow.getHeight() / 2f;
- float fromDegrees = 0f;
- float toDegrees = 0f;
- if (currentStatus == STATUS_PULL_TO_REFRESH) {
- fromDegrees = 180f;
- toDegrees = 360f;
- } else if (currentStatus == STATUS_RELEASE_TO_REFRESH) {
- fromDegrees = 0f;
- toDegrees = 180f;
- }
- RotateAnimation animation = new RotateAnimation(fromDegrees, toDegrees, pivotX, pivotY);
- animation.setDuration(100);
- animation.setFillAfter(true);
- arrow.startAnimation(animation);
- }
-
-
- private void refreshUpdatedAtValue() {
- lastUpdateTime = preferences.getLong(UPDATED_AT + mId, -1);
- long currentTime = System.currentTimeMillis();
- long timePassed = currentTime - lastUpdateTime;
- long timeIntoFormat;
- String updateAtValue;
- if (lastUpdateTime == -1) {
- updateAtValue = getResources().getString(R.string.not_updated_yet);
- } else if (timePassed < 0) {
- updateAtValue = getResources().getString(R.string.time_error);
- } else if (timePassed < ONE_MINUTE) {
- updateAtValue = getResources().getString(R.string.updated_just_now);
- } else if (timePassed < ONE_HOUR) {
- timeIntoFormat = timePassed / ONE_MINUTE;
- String value = timeIntoFormat + "分鐘";
- updateAtValue = String.format(getResources().getString(R.string.updated_at), value);
- } else if (timePassed < ONE_DAY) {
- timeIntoFormat = timePassed / ONE_HOUR;
- String value = timeIntoFormat + "小時";
- updateAtValue = String.format(getResources().getString(R.string.updated_at), value);
- } else if (timePassed < ONE_MONTH) {
- timeIntoFormat = timePassed / ONE_DAY;
- String value = timeIntoFormat + "天";
- updateAtValue = String.format(getResources().getString(R.string.updated_at), value);
- } else if (timePassed < ONE_YEAR) {
- timeIntoFormat = timePassed / ONE_MONTH;
- String value = timeIntoFormat + "個月";
- updateAtValue = String.format(getResources().getString(R.string.updated_at), value);
- } else {
- timeIntoFormat = timePassed / ONE_YEAR;
- String value = timeIntoFormat + "年";
- updateAtValue = String.format(getResources().getString(R.string.updated_at), value);
- }
- updateAt.setText(updateAtValue);
- }
-
-
- class RefreshingTask extends AsyncTask<Void, Integer, Void> {
-
- @Override
- protected Void doInBackground(Void... params) {
- int topMargin = headerLayoutParams.topMargin;
- while (true) {
- topMargin = topMargin + SCROLL_SPEED;
- if (topMargin <= 0) {
- topMargin = 0;
- break;
- }
- publishProgress(topMargin);
- sleep(10);
- }
- currentStatus = STATUS_REFRESHING;
- publishProgress(0);
- if (mListener != null) {
- mListener.onRefresh();
- }
- return null;
- }
-
- @Override
- protected void onProgressUpdate(Integer... topMargin) {
- updateHeaderView();
- headerLayoutParams.topMargin = topMargin[0];
- header.setLayoutParams(headerLayoutParams);
- }
-
- }
-
-
- class HideHeaderTask extends AsyncTask<Void, Integer, Integer> {
-
- @Override
- protected Integer doInBackground(Void... params) {
- int topMargin = headerLayoutParams.topMargin;
- while (true) {
- topMargin = topMargin + SCROLL_SPEED;
- if (topMargin <= hideHeaderHeight) {
- topMargin = hideHeaderHeight;
- break;
- }
- publishProgress(topMargin);
- sleep(10);
- }
- return topMargin;
- }
-
- @Override
- protected void onProgressUpdate(Integer... topMargin) {
- headerLayoutParams.topMargin = topMargin[0];
- header.setLayoutParams(headerLayoutParams);
- }
-
- @Override
- protected void onPostExecute(Integer topMargin) {
- headerLayoutParams.topMargin = topMargin;
- header.setLayoutParams(headerLayoutParams);
- currentStatus = STATUS_REFRESH_FINISHED;
- }
- }
-
-
- private void sleep(int time) {
- try {
- Thread.sleep(time);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
-
-
- public interface PullToRefreshListener {
-
-
- void onRefresh();
-
- }
-
- }</span>
這個類是整個下拉刷新功能中最重要的一個類,註釋已經寫得比較詳細了,我再簡單解釋一下。首先在RefreshableView的構造函數中動態添加了剛剛定義的pull_to_refresh這個佈局做爲下拉頭,而後在onLayout方法中將下拉頭向上偏移出了屏幕,再給ListView註冊了touch事件。以後每當手指在ListView上滑動時,onTouch方法就會執行。在onTouch方法中的第一行就調用了setIsAbleToPull方法來判斷ListView是否滾動到了最頂部,只有滾動到了最頂部纔會執行後面的代碼,不然就視爲正常的ListView滾動,不作任何處理。當ListView滾動到了最頂部時,若是手指還在向下拖動,就會改變下拉頭的偏移值,讓下拉頭顯示出來,下拉的距離設定爲手指移動距離的1/2,這樣纔會有拉力的感受。若是下拉的距離足夠大,在鬆手的時候就會執行刷新操做,若是距離不夠大,就僅僅從新隱藏下拉頭。ide
具體的刷新操做會在RefreshingTask中進行,其中在doInBackground方法中回調了PullToRefreshListener接口的onRefresh方法,這也是你們在使用RefreshableView時必需要去實現的一個接口,由於具體刷新的邏輯就應該寫在onRefresh方法中,後面會演示使用的方法。函數
另外每次在下拉的時候都還會調用updateHeaderView方法來改變下拉頭中的數據,好比箭頭方向的旋轉,下拉文字描述的改變等。更加深刻的理解請你們仔細去閱讀RefreshableView中的代碼。
如今咱們已經把下拉刷新的全部功能都完成了,接下來就要看一看如何在項目中引入下拉刷新了。打開或新建activity_main.xml做爲程序主界面的佈局,加入以下代碼:佈局
- <RelativeLayout 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"
- tools:context=".MainActivity" >
-
- <com.example.pulltorefreshtest.RefreshableView
- android:id="@+id/refreshable_view"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent" >
-
- <ListView
- android:id="@+id/list_view"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent" >
- </ListView>
- </com.example.pulltorefreshtest.RefreshableView>
-
- </RelativeLayout>
- <span style="font-size:14px;"><RelativeLayout 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"
- tools:context=".MainActivity" >
-
- <com.example.pulltorefreshtest.RefreshableView
- android:id="@+id/refreshable_view"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent" >
-
- <ListView
- android:id="@+id/list_view"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent" >
- </ListView>
- </com.example.pulltorefreshtest.RefreshableView>
-
- </RelativeLayout></span>
能夠看到,咱們在自定義的RefreshableView中加入了一個ListView,這就意味着給這個ListView加入了下拉刷新的功能,就是這麼簡單!
而後咱們再來看一下程序的主Activity,打開或新建MainActivity,加入以下代碼:this
- public class MainActivity extends Activity {
-
- RefreshableView refreshableView;
- ListView listView;
- ArrayAdapter<String> adapter;
- String[] items = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L" };
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- requestWindowFeature(Window.FEATURE_NO_TITLE);
- setContentView(R.layout.activity_main);
- refreshableView = (RefreshableView) findViewById(R.id.refreshable_view);
- listView = (ListView) findViewById(R.id.list_view);
- adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
- listView.setAdapter(adapter);
- refreshableView.setOnRefreshListener(new PullToRefreshListener() {
- @Override
- public void onRefresh() {
- try {
- Thread.sleep(3000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- refreshableView.finishRefreshing();
- }
- }, 0);
- }
-
- }
- <span style="font-size:14px;">public class MainActivity extends Activity {
-
- RefreshableView refreshableView;
- ListView listView;
- ArrayAdapter<String> adapter;
- String[] items = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L" };
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- requestWindowFeature(Window.FEATURE_NO_TITLE);
- setContentView(R.layout.activity_main);
- refreshableView = (RefreshableView) findViewById(R.id.refreshable_view);
- listView = (ListView) findViewById(R.id.list_view);
- adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
- listView.setAdapter(adapter);
- refreshableView.setOnRefreshListener(new PullToRefreshListener() {
- @Override
- public void onRefresh() {
- try {
- Thread.sleep(3000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- refreshableView.finishRefreshing();
- }
- }, 0);
- }
-
- }</span>
能夠看到,咱們經過調用RefreshableView的setOnRefreshListener方法註冊了一個監聽器,當ListView正在刷新時就會回調監聽器的onRefresh方法,刷新的具體邏輯就在這裏處理。並且這個方法已經自動開啓了線程,能夠直接在onRefresh方法中進行耗時操做,好比向服務器請求最新數據等,在這裏我就簡單讓線程睡眠3秒鐘。另外在onRefresh方法的最後,必定要調用RefreshableView中的finishRefreshing方法,這個方法是用來通知RefreshableView刷新結束了,否則咱們的ListView將一直處於正在刷新的狀態。
不知道你們有沒有注意到,setOnRefreshListener這個方法實際上是有兩個參數的,咱們剛剛也是傳入了一個不起眼的0。那這第二個參數是用來作什麼的呢?因爲RefreshableView比較智能,它會自動幫咱們記錄上次刷新完成的時間,而後下拉的時候會在下拉頭中顯示距上次刷新已過了多久。這是一個很是好用的功能,讓咱們不用再本身手動去記錄和計算時間了,可是卻存在一個問題。若是當前咱們的項目中有三個地方都使用到了下拉刷新的功能,如今在一處進行了刷新,其它兩處的時間也都會跟着改變!由於刷新完成的時間是記錄在配置文件中的,因爲在一處刷新更改了配置文件,致使在其它兩處讀取到的配置文件時間已是更改過的了。那解決方案是什麼?就是每一個用到下拉刷新的地方,給setOnRefreshListener方法的第二個參數中傳入不一樣的id就好了。這樣各處的上次刷新完成時間都是單獨記錄的,相互之間就不會再有影響。
好了,所有的代碼都在這裏了,讓咱們來運行一下,看看效果吧。spa
![](http://static.javashuo.com/static/loading.gif)
效果看起來仍是很是不錯的。咱們最後再來總結一下,在項目中引入ListView下拉刷新功能只需三步:
1. 在Activity的佈局文件中加入自定義的RefreshableView,並讓ListView包含在其中。
2. 在Activity中調用RefreshableView的setOnRefreshListener方法註冊回調接口。
3. 在onRefresh方法的最後,記得調用RefreshableView的finishRefreshing方法,通知刷新結束。
今後之後,在項目的任何地方,一分鐘引入下拉刷新功能妥妥的。
好了,今天的講解到此結束,有疑問的朋友請在下面留言。