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

Android 下拉刷新與上拉加載:以 android-pulltorefresh 開源庫實作

編輯:關於 Android 程式設計

為什麼需要它

App 呈現資訊時,不可能一次把全部資料拉回來。為了讓使用者能順手地「往下拉看更多、往下滑載入舊的」,動態分頁加載就成了標配。本文以開源專案 android-pulltorefresh 為基礎,走一遍完整實作。

這個庫的優勢在於支援面廣:ListView、ViewPager、WebView、ExpandableListView、GridView、(Horizontal) ScrollView、Fragment 都能上下左右拉動刷新,比只支援 ListView 的實作強大許多。而且它做出來的下拉刷新 ListView 在 item 不足一屏時不會顯示刷新提示,體驗更細膩。

步驟一:建立專案與資源檔

新建 Android 專案 SampleDemo,在 res/values 下建立 attrs.xml:

<!--?xml version=1.0 encoding=utf-8?-->
<resources>
    <declare-styleable name="PullToRefresh">
        <flag name="pullDownFromTop" value="0x1"></flag>
        <flag name="pullUpFromBottom" value="0x2"></flag>
        <flag name="both" value="0x3"></flag>
    </declare-styleable>
</resources>

並在 strings.xml 中定義提示文字:

<!--?xml version=1.0 encoding=utf-8?-->
<resources>
    <string name="app_name">SampleDemo</string>
    <string name="action_settings">Settings</string>
    <string name="pull_to_refresh_pull_down_label">滑動刷新</string>
    <string name="pull_to_refresh_release_label">釋放刷新</string>
    <string name="pull_to_refresh_refreshing_label">加載中</string>
    <string name="pull_to_refresh_tap_label">點擊刷新</string>
</resources>

步驟二:放入圖片資源

把刷新提示所需的箭頭等圖檔放進對應的 drawable 目錄。

步驟三:導入開源類檔

從 android-pulltorefresh 中把需要的類複製到自己的專案指定包內。本範例涉及:

com.handmark.pulltorefresh.library 下:
PullToRefreshAdapterViewBase.java、PullToRefreshBase.java、PullToRefreshListView.java

com.handmark.pulltorefresh.library.internal 下:
EmptyViewMethodAccessor.java、LoadingLayout.java

步驟四:實作非同步任務

用 AsyncTask 模擬一次網路請求,完成後依「上拉或下拉」把新資料塞進列表頭尾,再通知 Adapter 刷新。

import java.util.LinkedList;
import com.example.sampledemo.view.PullToRefreshListView;
import android.os.AsyncTask;
import android.widget.BaseAdapter;

public class PullTask extends AsyncTask<Void, String, String> {

    private PullToRefreshListView pullToRefreshListView; // 實作下拉刷新與上拉加載的 ListView
    private int pullState;      // 記錄是上拉還是下拉
    private BaseAdapter baseAdapter;   // 用於提醒 ListView 資料已更新
    private LinkedList<String> linkedList;

    public PullTask(PullToRefreshListView pullToRefreshListView, int pullState,
                    BaseAdapter baseAdapter, LinkedList<String> linkedList) {
        this.pullToRefreshListView = pullToRefreshListView;
        this.pullState = pullState;
        this.baseAdapter = baseAdapter;
        this.linkedList = linkedList;
    }

    @Override
    protected String doInBackground(Void... params) {
        try {
            Thread.sleep(1000); // 模擬網路延遲
        } catch (InterruptedException e) {
        }
        return StringTest;
    }

    @Override
    protected void onPostExecute(String result) {
        if (pullState == 1) {
            // pullDownFromTop value=0x1,下拉:新資料放頭部
            linkedList.addFirst(頂部數據);
        }
        if (pullState == 2) {
            // pullUpFromBottom value=0x2,上拉:新資料放尾部
            linkedList.addLast(底部數據);
        }
        baseAdapter.notifyDataSetChanged();
        pullToRefreshListView.onRefreshComplete();
        super.onPostExecute(result);
    }
}

步驟五:實作 Adapter

用 ViewHolder 模式減少 findViewById 呼叫次數,這是列表效能的基本功。

import java.util.LinkedList;
import com.example.sampledemo.R;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class PullAdapter extends BaseAdapter {

    private LinkedList<String> linkedList;
    private LayoutInflater mInflater;

    public PullAdapter(LinkedList<String> linkedList, Context context) {
        mInflater = LayoutInflater.from(context);
        this.linkedList = linkedList;
    }

    @Override
    public int getCount() {
        return linkedList.size();
    }

    @Override
    public Object getItem(int position) {
        return linkedList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = mInflater.inflate(R.layout.layout_main_listitem, null);
            holder.textView = (TextView) convertView.findViewById(R.id.textView);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        if (linkedList.size() > 0) {
            holder.textView.setText(linkedList.get(position));
        }
        return convertView;
    }

    private static class ViewHolder {
        TextView textView; // 資料顯示區域
    }
}

步驟六:三個版面檔

列表項 layout_main_listitem.xml:

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

    <TextView
        android:id="@+id/textView"
        android:gravity="left"
        android:layout_height="wrap_content"
        android:layout_marginTop="4dp"
        android:layout_width="match_parent"
        android:textColor="#99CC66"
        android:textSize="18dp" />

</LinearLayout>

滑動時出現的提示 pull_to_refresh_header.xml:

<!--?xml version=1.0 encoding=utf-8?-->
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_height="fill_parent"
    android:layout_width="fill_parent"
    android:paddingBottom="10dip"
    android:paddingTop="10dp">

    <TextView
        android:id="@+id/pull_to_refresh_text"
        android:layout_centerInParent="true"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="@string/pull_to_refresh_pull_down_label"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <ProgressBar
        android:id="@+id/pull_to_refresh_progress"
        android:indeterminate="true"
        android:layout_centerVertical="true"
        android:layout_height="wrap_content"
        android:layout_marginLeft="30dip"
        android:layout_marginRight="20dip"
        android:layout_width="wrap_content"
        android:visibility="gone" />

    <ImageView
        android:id="@+id/pull_to_refresh_image"
        android:layout_centerVertical="true"
        android:layout_height="wrap_content"
        android:layout_marginLeft="30dip"
        android:layout_marginRight="20dip"
        android:layout_width="wrap_content" />

</RelativeLayout>

主版面 activity_main.xml,注意 cp:mode="both" 代表同時啟用上下兩個方向:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:cp="https://schemas.android.com/apk/res/com.example.sampledemo"
    xmlns:tools="https://schemas.android.com/tools"
    android:background="#FFFFFF"
    android:layout_height="match_parent"
    android:layout_width="match_parent">

    <com.example.sampledemo.view.PullToRefreshListView
        android:id="@+id/pullrefresh"
        android:background="#FFFFFF"
        android:cacheColorHint="#00000000"
        android:divider="@android:color/black"
        android:dividerHeight="0.1dip"
        android:layout_height="fill_parent"
        android:layout_width="fill_parent"
        cp:mode="both">
    </com.example.sampledemo.view.PullToRefreshListView>

</RelativeLayout>

步驟七:串起 MainActivity

import java.util.Arrays;
import java.util.LinkedList;
import com.example.sampledemo.view.PullToRefreshBase.OnRefreshListener;
import com.example.sampledemo.view.PullToRefreshListView;
import com.example.sampledemo.view.adapter.PullAdapter;
import com.example.sampledemo.view.task.PullTask;
import android.os.Bundle;
import android.app.Activity;

public class MainActivity extends Activity {

    private LinkedList<String> mListItems;
    private PullToRefreshListView mPullRefreshListView;
    private PullAdapter pullAdapter;

    private String[] mStrings = {
        "初始數據01", "初始數據02", "初始數據03", "初始數據04", "初始數據05"
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initViews();
    }

    private void initViews() {
        mPullRefreshListView = (PullToRefreshListView) findViewById(R.id.pullrefresh);
        mPullRefreshListView.setOnRefreshListener(mOnrefreshListener);

        mListItems = new LinkedList<String>();
        mListItems.addAll(Arrays.asList(mStrings));

        pullAdapter = new PullAdapter(mListItems, MainActivity.this);
        mPullRefreshListView.getRefreshableView().setAdapter(pullAdapter);
    }

    OnRefreshListener mOnrefreshListener = new OnRefreshListener() {
        public void onRefresh() {
            PullTask pullTask = new PullTask(
                    mPullRefreshListView,
                    mPullRefreshListView.getRefreshType(),
                    pullAdapter,
                    mListItems);
            pullTask.execute();
        }
    };
}

下載地址

https://download.csdn.net/detail/ma_hoking/7276365

實作時要留意的三件事

記得呼叫 onRefreshComplete()。少了這一步,刷新提示會一直轉個不停。務必在 onPostExecute() 或錯誤處理分支中都確保它被呼叫,否則網路失敗時使用者只能看到無限 Loading。

分頁要有終止條件。伺服器端應回傳「是否還有下一頁」的資訊,全部載入完後要停止發送請求,並給使用者一個「沒有更多了」的提示,而不是讓他空拉。

非同步要用現代寫法。範例中的 AsyncTask 在 Android 11 之後已被標記為不建議使用,新專案請改用 Kotlin 協程、LiveData 搭配 ViewModel,或直接採用 Jetpack 的 Paging 3 元件——它已經把下拉刷新、上拉加載、資料快取與錯誤重試都處理好了。

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