編輯:關於 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);
}
}
用 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>
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 元件——它已經把下拉刷新、上拉加載、資料快取與錯誤重試都處理好了。
Android Service 學習筆記:AIDL 完整實例
註:本文是筆者稍早在 eoe 上發布的一篇文章。 由於每個應用程式都運行在自己的行程空間,而且可以從應用程式的 UI 啟動另一個服務行程,跨行程之間經常需要傳遞物件。在
安卓模仿 2048 小遊戲:從啟動頁到核心合併邏輯
這是一個以 Android 原生方式模仿 2048 的小專案。它包含啟動頁、登入頁、主遊戲頁、卡片模型、手勢合併邏輯與簡單動畫,可以作為自定義遊戲 View 的練習。
JNI 入門教學:在 Android 中透過 JNI 呼叫 C
一、JNI 是什麼 JNI 是 Java Native Interface 的縮寫,中文稱為 Java 本地呼叫。從 Java 1.1 起,JNI 就成為 Java 平台
Android 性能優化:如何縮短應用啟動時間
一、先搞清楚啟動方式的差別 Android 中應用的啟動方式大致可分為兩類: 冷啟動:啟動應用時背景沒有該應用的行程,系統會重新 fork 一個新行程分配給它。 熱啟動