Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 下拉刷新完全解析:一分鐘實作下拉刷新功能(附源碼)

編輯:Android 開發實例

最近專案中需要用到 ListView 的下拉刷新功能。起初想省事,直接從網上找現成的方案,但試了多個版本後發現效果都不理想——有些功能不完整或有 Bug,有些使用起來太過複雜,十全十美的還真不好找。於是乾脆自己動手實作了一種非常簡單的下拉刷新方案,這裡就拿出來與大家分享。相信讀完本文後,你也能在自己的專案裡一分鐘導入下拉刷新功能。

實作原理

這裡採用的方案是「組合 View」:先自訂一個繼承自 LinearLayout 的佈局,在其中加入「下拉頭」與 ListView 兩個子元素並縱向排列。初始化時讓下拉頭向上偏移出螢幕,這樣我們只看得到 ListView。接著監聽 ListView 的 touch 事件,當 ListView 已滾動到頂部且手指仍向下拉時,就顯示下拉頭;松手後執行刷新,再將下拉頭隱藏。原理示意圖如下:

第一步:定義下拉頭佈局

新建一個專案 PullToRefreshTest,並定義下拉頭佈局檔 pull_to_refresh.xml:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://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>

這個佈局包含了一個下拉指示箭頭、一個狀態文字提示,以及上次更新時間;另外還有一個隱藏的旋轉進度條,只有在刷新時才會顯示。

第二步:字串資源

佈局中引用的字串都放在 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>

第三步:核心類別 RefreshableView

接著建立繼承自 LinearLayout 的 RefreshableView,這是整个下拉刷新功能中最重要的一個類別。它在建構子中動態加入下拉頭佈局,於 onLayout() 中把下拉頭向上偏移出螢幕,並為 ListView 註冊 touch 事件;每當手指滑動時,onTouch() 便會執行刷新邏輯:

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;
 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 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);
 }
 /** 進行關鍵初始化:將下拉頭向上偏移隱藏,給 ListView 注冊 touch 事件。 */
 @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;
  }
 }
 /** 當 ListView 被觸摸時調用,處理下拉刷新的具體邏輯。 */
 @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;
 }
 }
 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;
  }
 }
 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 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();
 }
}

簡單來說:onTouch() 的第一行會呼叫 setIsAbleToPull() 判斷 ListView 是否滾動到最頂部,只有滾到頂部才會處理後續邏輯。下拉時會改變下拉頭的偏移值讓它顯示出來,下拉距離設為手指移動距離的 1/2,以營造拉力感。若距離足夠大,松手時便觸發刷新;否則僅重新隱藏下拉頭。具體刷新在 RefreshingTask 中進行,並回呼 PullToRefreshListener.onRefresh()。

第四步:在專案中引入

在主佈局 activity_main.xml 中加入自訂的 RefreshableView,並讓 ListView 包含其中:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://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>

可以看到,只要把 ListView 放進自訂的 RefreshableView 裡,就等於為它加上了下拉刷新功能,就是這麼簡單!

接著在 MainActivity 中註冊監聽器,刷新邏輯寫在 onRefresh() 中:

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);
 }
}

透過 setOnRefreshListener() 註冊監聽器後,當 ListView 刷新時便會回呼 onRefresh()。這個方法已自動開啟執行緒,可直接在其中進行耗時操作(例如向伺服器請求最新資料),範例中僅讓執行緒睡眠 3 秒。特別注意,在 onRefresh() 的最後一定要呼叫 finishRefreshing(),否則 ListView 會一直停留在刷新狀態。

至於 setOnRefreshListener() 的第二個參數(範例中傳入的 0)作用為何?由於 RefreshableView 會自動記錄上次刷新完成的時間,並在下拉時顯示距離上次刷新過了多久。但如果專案中有多處使用下拉刷新,一處刷新會連帶改變其他地方的時間。解法就是:每個用到下拉刷新的地方,傳入不同的 id,這樣各處的更新時間便各自獨立、互不影響。

執行後的效果如下:

最後總結一下,在專案中導入 ListView 下拉刷新功能只需三步:

1. 在 Activity 的佈局檔中加入自訂的 RefreshableView,並讓 ListView 包含其中。
2. 在 Activity 中呼叫 setOnRefreshListener() 註冊回呼介面。
3. 在 onRefresh() 的最後呼叫 finishRefreshing(),通知刷新結束。

從此以後,在任何地方一分鐘導入下拉刷新功能,輕鬆搞定。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved