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

Android 用 PullToRefresh 實作下拉刷新與上拉加載

編輯:關於 Android 程式設計

先放一張執行結果圖,如果看著順眼,就繼續往下讀。

延伸閱讀:分享 Android 中 pullToRefresh 的使用心得

專案已同步至 GitHub:https://github.com/nanchen2251/pullToRefreshDemo

一、把庫引入專案

Android Studio 雖然可以直接在 app 的 module 設定裡搜尋依賴,但套件名帶有「-」時必須原樣寫入,不能用空白代替。為了真正弄清楚它在做什麼,建議還是到官方倉庫看一遍:https://github.com/chrisbanes/Android-PullToRefresh

從 git 下載後,透過 Studio 的 Import Module 匯入 library,並把 library 的 gradle 檔與自己的專案對齊:

 apply plugin: 'com.android.library' android { compileSdkVersion 23 buildToolsVersion "24.0.0" defaultConfig { minSdkVersion 18 targetSdkVersion 23 } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt' } } }

接著在 app 模組聲明依賴,把兩者關聯起來。

打開 library 會看到相當豐富的內容:除了 ListView,它還支援 GridView、ScrollView 等,覆蓋面很廣。至於能否與正當紅的 RecyclerView 搭配,筆者尚未嘗試。

二、在版面配置中放入控制項

因為用到了自訂屬性,記得加上 xmlns:app 命名空間:

 <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://schemas.android.com/tools" xmlns:app="https://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.nanchen.pulltorefreshdemo.MainActivity"> <com.handmark.pulltorefresh.library.PullToRefreshListView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/main_pull_refresh_lv" app:ptrAnimation app:ptrHeaderBackground="@android:color/transparent" app:ptrHeaderTextColor="#919191"/> </RelativeLayout>

三、準備資料與項目版面

這裡用的是它內建的 ListView,所以需要一個 Java Bean 與一份 item 配置。

 package com.example.nanchen.pulltorefreshdemo; /** * Created by 南塵 on 16-7-20. */ public class Music { private String title; private String singer; public Music() { } public Music(String title, String singer) { this.title = title; this.singer = singer; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getSinger() { return singer; } public void setSinger(String singer) { this.singer = singer; } }

list_item.xml:

 <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginLeft="20dp" android:layout_marginRight="20dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/item_title" android:text="歌曲1" android:textSize="20sp" android:layout_alignParentLeft="true"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/item_singer" android:textSize="20sp" android:text="歌手1" android:layout_alignParentRight="true"/> </RelativeLayout>

四、Activity 中的組裝

用法相當直觀。下面用 AsyncTask 模擬異步取數,並自訂 Adapter;之所以把 Adapter 寫成靜態內部類,是為了避免持有 Activity 參考而埋下記憶體洩漏的隱憂,好處不少。

 package com.example.nanchen.pulltorefreshdemo; import android.content.Context; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.TextView; import com.handmark.pulltorefresh.library.ILoadingLayout; import com.handmark.pulltorefresh.library.PullToRefreshBase; import com.handmark.pulltorefresh.library.PullToRefreshListView; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { private PullToRefreshListView refresh_lv; private List<Music> list; private DataAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); refresh_lv = (PullToRefreshListView) findViewById(R.id.main_pull_refresh_lv); list = new ArrayList<>(); //設置可上拉刷新和下拉刷新 refresh_lv.setMode(PullToRefreshBase.Mode.BOTH); //設置刷新時顯示的文本 ILoadingLayout startLayout = refresh_lv.getLoadingLayoutProxy(true,false); startLayout.setPullLabel("正在下拉刷新..."); startLayout.setRefreshingLabel("正在玩命加載中..."); startLayout.setReleaseLabel("放開以刷新"); ILoadingLayout endLayout = refresh_lv.getLoadingLayoutProxy(false,true); endLayout.setPullLabel("正在上拉刷新..."); endLayout.setRefreshingLabel("正在玩命加載中..."); endLayout.setReleaseLabel("放開以刷新"); refresh_lv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() { @Override public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) { new LoadDataAsyncTask(MainActivity.this).execute(); } @Override public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) { new LoadDataAsyncTask(MainActivity.this).execute(); } }); loadData(); adapter = new DataAdapter(this,list); refresh_lv.setAdapter(adapter); } private int count = 1; private void loadData(){ for (int i = 0; i < 10; i++) { list.add(new Music("歌曲"+count,"歌手"+count)); count++; } } /** * 異步下載任務 */ private static class LoadDataAsyncTask extends AsyncTask<Void,Void,String>{ private MainActivity mainActivity; public LoadDataAsyncTask(MainActivity mainActivity) { this.mainActivity = mainActivity; } @Override protected String doInBackground(Void... params) { try { Thread.sleep(2000); mainActivity.loadData(); return "seccess"; } catch (InterruptedException e) { e.printStackTrace(); } return null; } /** * 完成時的方法 */ @Override protected void onPostExecute(String s) { super.onPostExecute(s); if (s.equals("seccess")){ mainActivity.adapter.notifyDataSetChanged(); mainActivity.refresh_lv.onRefreshComplete();//刷新完成 } } } /** * 自定義適配器 */ private static class DataAdapter extends BaseAdapter{ private Context context; private List<Music> list; public DataAdapter(Context context, List<Music> list) { this.context = context; this.list = list; } @Override public int getCount() { if (list != null){ return list.size(); } return 0; } @Override public Object getItem(int position) { return list.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder vh; if (convertView == null){ convertView = LayoutInflater.from(context).inflate(R.layout.list_item,parent,false); vh = new ViewHolder(); vh.tv_title = (TextView) convertView.findViewById(R.id.item_title); vh.tv_singer = (TextView) convertView.findViewById(R.id.item_singer); convertView.setTag(vh); }else{ vh = (ViewHolder) convertView.getTag(); } Music music = (Music) getItem(position); vh.tv_title.setText(music.getTitle()); vh.tv_singer.setText(music.getSinger()); return convertView; } class ViewHolder{ TextView tv_title; TextView tv_singer; } } }

幾個實作重點值得留意:透過 setMode(BOTH) 同時打開上下兩個方向;用 getLoadingLayoutProxy 分別客製頭尾兩側的提示文字;下拉與上拉都會回呼,記得在 onRefreshComplete 之前更新資料,否則提示狀態會卡住。

以上就是 PullToRefresh 實現上拉加載與下拉刷新的完整流程。若有任何疑問,歡迎留言討論。

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