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

用 PullToRefresh 實現下拉刷新與上拉加載

編輯:關於 Android 程式設計

PullToRefresh 是一套設計精良的下拉刷新庫,支援 ListView、ExpandableListView、GridView、WebView 等多種常見需要刷新的 View 類型,使用起來十分方便。(下載地址:https://github.com/chrisbanes/Android-PullToRefresh)

下載後將它作為 library 匯入 Eclipse,再於自己的工程中引用即可。

一、下拉刷新

1. 在布局檔中加入想用的 View,例如這裡使用支援下拉刷新的 ExpandableListView:

 <com.handmark.pulltorefresh.library.PullToRefreshExpandableListView android:id="@+id/expand_list" android:layout_width="match_parent" android:layout_height="match_parent" /> 

2. 在 Activity 中做簡單設定:

 mExpandList = (PullToRefreshExpandableListView) rootView.findViewById(R.id.expand_list); mExpandList.getRefreshableView().setGroupIndicator(null); mExpandList.getRefreshableView().setDivider(null); mExpandList.getRefreshableView().setSelector(android.R.color.transparent); mExpandList.getRefreshableView().setOnGroupClickListener(this); mExpandList.setOnRefreshListener(this); 

第一行找到 View,最後一行加上刷新監聽器,中間幾行是對 ExpandableListView 的額外設定。

3. 下拉刷新時執行的 onRefresh():

 @Override public void onRefresh(PullToRefreshBase<ExpandableListView> refreshView) { if (!isRefreshing) { isRefreshing = true; updateList(true); } else { mExpandList.onRefreshComplete(); } }

由於通常會另開執行緒取資料,這裡加了一個判斷:若已在載入中就直接 onRefreshComplete() 收起下拉;否則開新執行緒取資料,取完別忘了也要呼叫 onRefreshComplete()。

二、上拉加載

PullToRefresh 本身同時支援下拉與上拉,因此只要把上拉「改造成」上拉加載即可。

1. 設定 Mode

 // set mode to BOTH mExpandList.setMode(Mode.BOTH); mExpandList.getLoadingLayoutProxy(false, true).setPullLabel(getString(R.string.pull_to_load)); mExpandList.getLoadingLayoutProxy(false, true).setRefreshingLabel(getString(R.string.loading)); mExpandList.getLoadingLayoutProxy(false, true).setReleaseLabel(getString(R.string.release_to_load)); 

把 Mode 設為 Mode.BOTH 後,上拉與下拉都會觸發 onRefresh()。由於上方要顯示「下拉刷新」、下方要顯示「上拉加載」,因此後三行是修改下方部分的文字,getLoadingLayoutProxy(false, true) 可依實際感受調整。

2. 如何區分下拉與上拉

網上有些做法是用 onScrollListener 判斷,但並不嚴謹。這裡依賴 header 還是 footer 處於可見狀態來區分:下拉時 header 一定可見,反之 footer 一定可見。由於 PullToRefreshExpandableListView 未提供這樣的介面,可以小改引入的庫——在 com.handmark.pulltorefresh.library 下的 PullToRefreshAdapterViewBase.java 中加入兩個方法:

 public boolean isHeaderShown() { return getHeaderLayout().isShown(); } public boolean isFooterShown() { return getFooterLayout().isShown(); } 

重新編譯庫工程與自己的工程後,在 onRefresh() 中這樣使用:

 @Override public void onRefresh(PullToRefreshBase<ExpandableListView> refreshView) { if (!isRefreshing) { isRefreshing = true; if (mExpandList.isHeaderShown()) { Utils.LOGD("pull-to-refresh"); refreshOnlineStatus(true); } else if (mExpandList.isFooterShown()) { Utils.LOGD("pull-to-load-more"); loadNextPage(); } } else { mExpandList.onRefreshComplete(); } }

如此一來,就能用 PullToRefresh 同時實現下拉刷新與上拉加載。

補充的兩個坑

1.要實現上拉監聽,只需實作 OnRefreshListener2,同時別忘了 setMode(Mode.BOTH)。
2.PullToRefreshListView 有個已知 BUG:在 XML 布局中,不能一開始就把它的 visibility 設為 GONE,否則之後在程式碼中設為 VISIBLE 也不會生效。

最後放上一張效果圖:

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