Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 下拉刷新庫 PullToRefresh 深度剖析與實作入門

編輯:關於 Android 程式設計

在 Android 應用開發裡,即時獲取網路資料並刷新清單是非常常見的需求。舉例來說,即時查看好友的線上狀態、載入更多社群動態,或是論壇客戶端分批顯示文章列表,都離不開「下拉刷新」這個互動模式。開源專案 android-pulltorefresh 正是為此而生,它提供了直覺的下滑手勢觸發刷新機制,只要稍加調整,就能輕鬆整合進自己的專案。

一、專案來源

讀者可透過官方開源倉儲取得原始碼,下載後匯入 IDE 即可開始研究與使用。

二、工程結構解析

整個庫的核心圍繞著幾個關鍵類別與資源檔展開。

PullToRefreshListView.java

這是整個元件的基礎。它自訂了 OnRefreshListener 介面來監聽刷新動作,其中包含兩個重要回呼:

  • onRefresh():觸發刷新時呼叫,通常會在清單頂部顯示刷新進度條。
  • onRefreshComplete():刷新完成後呼叫,用來把清單還原為正常狀態。

以下為關鍵實作片段:

public class PullToRefreshListView extends ListView implements OnScrollListener {
    /** 當清單需要刷新時觸發的回呼介面 */
    public interface OnRefreshListener {
        void onRefresh();
    }

    /** 刷新完成後重設清單狀態,並可帶入最後更新時間 */
    public void onRefreshComplete(CharSequence lastUpdated) {
        setLastUpdated(lastUpdated);
        onRefreshComplete();
    }

    /** 刷新完成後重設清單狀態 */
    public void onRefreshComplete() {
        Log.d(TAG, "onRefreshComplete");
        resetHeader();
        // 若載入完成時刷新檢視仍顯示中,捲動到下一個項目
        if (getFirstVisiblePosition() == 0) {
            invalidateViews();
            setSelection(1);
        }
    }
}

pull_to_refresh_header.xml

這個版面檔負責呈現清單頂部的刷新進度條。在 PullToRefreshListView.java 中,透過下列程式碼把這個子版面插入到清單最上方:

private LayoutInflater mInflater;
private RelativeLayout mRefreshView;

mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// 載入刷新頁首版面
mRefreshView = (RelativeLayout) mInflater.inflate(R.layout.pull_to_refresh_header, this, false);
// 把頁首加入 ListView
addHeaderView(mRefreshView);

PullToRefreshActivity.java(主要 Activity)與 pull_to_refresh.xml

版面檔中,PullToRefreshListView 直接取代了標準的 ListView 元件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <!-- PullToRefreshListView 取代標準的 ListView -->
    <com.markupartist.android.widget.PullToRefreshListView
        android:id="@+id/android:list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />
</LinearLayout>

補充說明:如果 Activity 繼承自 ListActivity,其版面中必須且只能包含一個 id 為 @id/android:list 的 ListView,如此一來我們便能方便地覆寫各項清單操作方法來實現自訂功能。

三、PullToRefreshActivity.java 完整範例

範例以一個額外的資料陣列 mExtras 模擬分批載入,當資料全部顯示完畢後就不再刷新,反而會提示「No More Messages」。這樣的設計能避免使用者無意義地持續下拉。

package com.markupartist.android.example.pulltorefresh;

import java.util.Arrays;
import java.util.LinkedList;
import android.annotation.SuppressLint;
import android.app.ListActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import com.markupartist.android.widget.PullToRefreshListView;
import com.markupartist.android.widget.PullToRefreshListView.OnRefreshListener;

@SuppressLint("NewApi")
public class PullToRefreshActivity extends ListActivity {
    private LinkedList<String> mListItems;
    int count = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pull_to_refresh);

        // 註冊刷新監聽器
        ((PullToRefreshListView) getListView()).setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (count < mExtras.length) {
                    new GetDataTask().execute(count++);
                } else {
                    Toast.makeText(getApplicationContext(), "No More Messages", Toast.LENGTH_LONG).show();
                    ((PullToRefreshListView) getListView()).onRefreshComplete();
                }
            }
        });

        mListItems = new LinkedList<String>();
        mListItems.addAll(Arrays.asList(mStrings));
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mListItems);
        setListAdapter(adapter);
    }

    private class GetDataTask extends AsyncTask<Integer, Void, String[]> {
        private int count;

        @Override
        protected String[] doInBackground(Integer... params) {
            count = params[0];
            try {
                Thread.sleep(2000); // 模擬背景非同步工作
            } catch (InterruptedException e) {
                // 忽略中斷
            }
            return mStrings;
        }

        @Override
        protected void onPostExecute(String[] result) {
            mListItems.addFirst(mExtras[count]); // 刷新後把新資料插入到最前方
            ((PullToRefreshListView) getListView()).onRefreshComplete();
        }
    }

    private String[] mStrings = { "Abbaye de Belloc", "Abbaye du Mont des Cats", "Abertam", "Abondance", "Ackawi", "Acorn", "Adelost", "Affidelice au Chablis", "Afuega'l Pitu", "Airag", "Airedale", "Aisy Cendre", "Allgauer Emmentaler" };
    private String[] mExtras = { "extra1", "extra2", "extra3" };
}

透過 AsyncTask 在背景執行耗時操作,再於 onPostExecute 中更新介面並呼叫 onRefreshComplete(),就能打造流暢且不阻塞主執行緒的下拉刷新體驗。

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