Android PullToRefresh (ListView GridView 下拉刷新) 使用詳解

轉載請標明出處:http://blog.csdn.net/lmj623565791/article/details/38238749,本文出自:【張鴻洋的博客】

羣裏一哥們今天聊天偶然提到這個git hub上的控件:pull-to-refresh ,有興趣的看下,例子中的功能極其強大,支持很多控件。本篇博客詳細給大家介紹下ListView和GridView利用pull-to-rerfesh 實現下拉刷新和上拉加載更多。

1、ListView下拉刷新快速入門

pull-to-refresh對ListView進行了封裝,叫做:PullToRefreshListView,用法和listview沒什麼區別,下面看demo.

佈局文件:

[html] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent" >  
  5.   
  6.     <com.handmark.pulltorefresh.library.PullToRefreshListView  
  7.         xmlns:ptr="http://schemas.android.com/apk/res-auto"  
  8.         android:id="@+id/pull_refresh_list"  
  9.         android:layout_width="fill_parent"  
  10.         android:layout_height="fill_parent"  
  11.         android:cacheColorHint="#00000000"  
  12.         android:divider="#19000000"  
  13.         android:dividerHeight="4dp"  
  14.         android:fadingEdge="none"  
  15.         android:fastScrollEnabled="false"  
  16.         android:footerDividersEnabled="false"  
  17.         android:headerDividersEnabled="false"  
  18.         android:smoothScrollbar="true" >  
  19.     </com.handmark.pulltorefresh.library.PullToRefreshListView>  
  20.   
  21. </RelativeLayout>  

聲明瞭一個PullToRefreshListView,裏面所有的屬性都是ListView的,沒有任何其他屬性,當然了PullToRefreshListView也提供了很多配置的屬性,後面會詳細介紹。

Activity的代碼:

[java] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. package com.example.zhy_pulltorefreash_chenyoca;  
  2.   
  3. import java.util.LinkedList;  
  4.   
  5. import android.app.Activity;  
  6. import android.os.AsyncTask;  
  7. import android.os.Bundle;  
  8. import android.text.format.DateUtils;  
  9. import android.widget.ArrayAdapter;  
  10. import android.widget.ListView;  
  11.   
  12. import com.handmark.pulltorefresh.library.PullToRefreshBase;  
  13. import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;  
  14. import com.handmark.pulltorefresh.library.PullToRefreshListView;  
  15.   
  16. public class PullToRefreshListActivity extends Activity  
  17. {  
  18.   
  19.     private LinkedList<String> mListItems;  
  20.     /** 
  21.      * 上拉刷新的控件 
  22.      */  
  23.     private PullToRefreshListView mPullRefreshListView;  
  24.   
  25.     private ArrayAdapter<String> mAdapter;  
  26.   
  27.     private int mItemCount = 9;  
  28.   
  29.     @Override  
  30.     protected void onCreate(Bundle savedInstanceState)  
  31.     {  
  32.         super.onCreate(savedInstanceState);  
  33.         setContentView(R.layout.activity_main);  
  34.         // 得到控件  
  35.         mPullRefreshListView = (PullToRefreshListView) findViewById(R.id.pull_refresh_list);  
  36.         //初始化數據  
  37.         initDatas();  
  38.         //設置適配器  
  39.         mAdapter = new ArrayAdapter<String>(this,  
  40.                 android.R.layout.simple_list_item_1, mListItems);  
  41.         mPullRefreshListView.setAdapter(mAdapter);  
  42.         // 設置監聽事件  
  43.         mPullRefreshListView  
  44.                 .setOnRefreshListener(new OnRefreshListener<ListView>()  
  45.                 {  
  46.                     @Override  
  47.                     public void onRefresh(  
  48.                             PullToRefreshBase<ListView> refreshView)  
  49.                     {  
  50.                         String label = DateUtils.formatDateTime(  
  51.                                 getApplicationContext(),  
  52.                                 System.currentTimeMillis(),  
  53.                                 DateUtils.FORMAT_SHOW_TIME  
  54.                                         | DateUtils.FORMAT_SHOW_DATE  
  55.                                         | DateUtils.FORMAT_ABBREV_ALL);  
  56.                         // 顯示最後更新的時間  
  57.                         refreshView.getLoadingLayoutProxy()  
  58.                                 .setLastUpdatedLabel(label);  
  59.   
  60.                         // 模擬加載任務  
  61.                         new GetDataTask().execute();  
  62.                     }  
  63.                 });  
  64.   
  65.     }  
  66.   
  67.     private void initDatas()  
  68.     {  
  69.         // 初始化數據和數據源  
  70.         mListItems = new LinkedList<String>();  
  71.   
  72.         for (int i = 0; i < mItemCount; i++)  
  73.         {  
  74.             mListItems.add("" + i);  
  75.         }  
  76.     }  
  77.   
  78.     private class GetDataTask extends AsyncTask<Void, Void, String>  
  79.     {  
  80.   
  81.         @Override  
  82.         protected String doInBackground(Void... params)  
  83.         {  
  84.             try  
  85.             {  
  86.                 Thread.sleep(2000);  
  87.             } catch (InterruptedException e)  
  88.             {  
  89.             }  
  90.             return "" + (mItemCount++);  
  91.         }  
  92.   
  93.         @Override  
  94.         protected void onPostExecute(String result)  
  95.         {  
  96.             mListItems.add(result);  
  97.             mAdapter.notifyDataSetChanged();  
  98.             // Call onRefreshComplete when the list has been refreshed.  
  99.             mPullRefreshListView.onRefreshComplete();  
  100.         }  
  101.     }  
  102.   
  103. }  

代碼極其簡單,得到PullToRefreshListView控件,然後像ListView一樣設置數據集。當然了,我們有下拉刷新,所以必須設置下拉刷新的回調:

setOnRefreshListener(new OnRefreshListener<ListView>(){}

我們在回調中模擬了一個異步任務,加載了一個Item。

效果圖:


下拉時,執行我們的GetDataTask任務,任務執行完成後在onPostExecute中 調用mPullRefreshListView.onRefreshComplete();完成刷新。

是不是分分鐘實現下拉刷新。當然了,你可能會有疑問,下拉刷新的指示器上的文字可以自定義嗎?那個圖片可以換成箭頭嗎?說好的上拉加載更多呢?後面會一一添加~

2、添加上拉加載更多

如過希望實現上拉加載更多,那麼首先需要在佈局文件的聲明屬性中添加一個屬性,用於指定目前的下拉模式:

[html] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent" >  
  5.   
  6.     <com.handmark.pulltorefresh.library.PullToRefreshListView  
  7.         xmlns:ptr="http://schemas.android.com/apk/res-auto"  
  8.         android:id="@+id/pull_refresh_list"  
  9.         android:layout_width="fill_parent"  
  10.         android:layout_height="fill_parent"  
  11.         android:cacheColorHint="#00000000"  
  12.         android:divider="#19000000"  
  13.         android:dividerHeight="4dp"  
  14.         android:fadingEdge="none"  
  15.         android:fastScrollEnabled="false"  
  16.         android:footerDividersEnabled="false"  
  17.         android:headerDividersEnabled="false"  
  18.         android:smoothScrollbar="true"  
  19.         ptr:ptrMode="both" >  
  20.     </com.handmark.pulltorefresh.library.PullToRefreshListView>  
  21.   
  22. </RelativeLayout>  
我們添加了一個屬性:ptr:ptrMode="both" ,意思:上拉和下拉都支持。

可選值爲:disabled(禁用下拉刷新),pullFromStart(僅支持下拉刷新),pullFromEnd(僅支持上拉刷新),both(二者都支持),manualOnly(只允許手動觸發)

當然了,如果你不喜歡在佈局文件中指定,完全可以使用代碼設置,在onCreate裏面寫:mPullRefreshListView.setMode(Mode.BOTH);//設置你需要的模式

設置了模式爲雙向都支持,當然必須爲上拉和下拉分別設置回調,請看下面的代碼:

[java] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. package com.example.zhy_pulltorefreash_chenyoca;  
  2.   
  3. import java.util.LinkedList;  
  4.   
  5. import android.app.Activity;  
  6. import android.os.AsyncTask;  
  7. import android.os.Bundle;  
  8. import android.text.format.DateUtils;  
  9. import android.util.Log;  
  10. import android.widget.ArrayAdapter;  
  11. import android.widget.ListView;  
  12.   
  13. import com.handmark.pulltorefresh.library.PullToRefreshBase;  
  14. import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;  
  15. import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;  
  16. import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;  
  17. import com.handmark.pulltorefresh.library.PullToRefreshListView;  
  18.   
  19. public class PullToRefreshListActivity extends Activity  
  20. {  
  21.   
  22.     private LinkedList<String> mListItems;  
  23.     /** 
  24.      * 上拉刷新的控件 
  25.      */  
  26.     private PullToRefreshListView mPullRefreshListView;  
  27.   
  28.     private ArrayAdapter<String> mAdapter;  
  29.   
  30.     private int mItemCount = 9;  
  31.   
  32.     @Override  
  33.     protected void onCreate(Bundle savedInstanceState)  
  34.     {  
  35.         super.onCreate(savedInstanceState);  
  36.         setContentView(R.layout.activity_main);  
  37.         // 得到控件  
  38.         mPullRefreshListView = (PullToRefreshListView) findViewById(R.id.pull_refresh_list);  
  39.         mPullRefreshListView.setMode(Mode.BOTH);  
  40.         // 初始化數據  
  41.         initDatas();  
  42.         // 設置適配器  
  43.         mAdapter = new ArrayAdapter<String>(this,  
  44.                 android.R.layout.simple_list_item_1, mListItems);  
  45.         mPullRefreshListView.setAdapter(mAdapter);  
  46.   
  47.         mPullRefreshListView  
  48.                 .setOnRefreshListener(new OnRefreshListener2<ListView>()  
  49.                 {  
  50.                     @Override  
  51.                     public void onPullDownToRefresh(  
  52.                             PullToRefreshBase<ListView> refreshView)  
  53.                     {  
  54.                         Log.e("TAG""onPullDownToRefresh");  
  55.                         //這裏寫下拉刷新的任務  
  56.                         new GetDataTask().execute();  
  57.                     }  
  58.   
  59.                     @Override  
  60.                     public void onPullUpToRefresh(  
  61.                             PullToRefreshBase<ListView> refreshView)  
  62.                     {  
  63.                         Log.e("TAG""onPullUpToRefresh");  
  64.                         //這裏寫上拉加載更多的任務  
  65.                         new GetDataTask().execute();  
  66.                     }  
  67.                 });  
  68.   
  69.     }  
  70.   
  71.     private void initDatas()  
  72.     {  
  73.         // 初始化數據和數據源  
  74.         mListItems = new LinkedList<String>();  
  75.   
  76.         for (int i = 0; i < mItemCount; i++)  
  77.         {  
  78.             mListItems.add("" + i);  
  79.         }  
  80.     }  
  81.   
  82.     private class GetDataTask extends AsyncTask<Void, Void, String>  
  83.     {  
  84.   
  85.         @Override  
  86.         protected String doInBackground(Void... params)  
  87.         {  
  88.             try  
  89.             {  
  90.                 Thread.sleep(2000);  
  91.             } catch (InterruptedException e)  
  92.             {  
  93.             }  
  94.             return "" + (mItemCount++);  
  95.         }  
  96.   
  97.         @Override  
  98.         protected void onPostExecute(String result)  
  99.         {  
  100.             mListItems.add(result);  
  101.             mAdapter.notifyDataSetChanged();  
  102.             // Call onRefreshComplete when the list has been refreshed.  
  103.             mPullRefreshListView.onRefreshComplete();  
  104.         }  
  105.     }  

和第一段的代碼只有一個地方有區別,可能很難發現:
mPullRefreshListView.setOnRefreshListener(new OnRefreshListener2<ListView>(){});注意這裏的接口類型是OnRefreshListener2,多了個2,和上面的不一樣,這個接口包含兩個方法,一個上拉回調,一個下拉回調。好了,這樣我們就成功添加了上拉與下拉,並且分別可以控制其回調代碼。

效果圖:


咋樣,是不是也很簡單~注:如果你的上拉和下拉需求是執行一樣的代碼,那麼你可以繼續註冊OnRefreshListener接口,上拉和下拉都會執行同一個方法。

接下來介紹如何使用帶下拉刷新和加載更多的的GridView和自定義樣式~

3、帶下拉和上拉的GridView ( PullToRefreshGridView )

同樣的pull-to-refresh把GridView封裝爲:PullToRefreshGridView 。用法和PullToRefreshListView一摸一樣~

首先看主佈局文件:

[html] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <!-- The PullToRefreshGridView replaces a standard GridView widget. -->  
  8.   
  9.     <com.handmark.pulltorefresh.library.PullToRefreshGridView  
  10.         xmlns:ptr="http://schemas.android.com/apk/res-auto"  
  11.         android:id="@+id/pull_refresh_grid"  
  12.         android:layout_width="fill_parent"  
  13.         android:layout_height="fill_parent"  
  14.         android:columnWidth="100dp"  
  15.         android:gravity="center_horizontal"  
  16.         android:horizontalSpacing="1dp"  
  17.         android:numColumns="auto_fit"  
  18.         android:stretchMode="columnWidth"  
  19.         android:verticalSpacing="1dp"  
  20.         ptr:ptrDrawable="@drawable/ic_launcher"  
  21.         ptr:ptrMode="both" />  
  22.   
  23. </LinearLayout>  
PullToRefreshGridView 的item的佈局文件:

[html] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <TextView xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:id="@+id/id_grid_item_text"  
  4.     android:layout_width="100dp"  
  5.     android:gravity="center"  
  6.     android:textColor="#ffffff"  
  7.     android:textSize="16sp"  
  8.     android:background="#000000"  
  9.     android:layout_height="100dp" />  

接下來就是Activity的代碼了:

[java] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. public class PullToRefreshGridActivity extends Activity  
  2. {  
  3.     private LinkedList<String> mListItems;  
  4.     private PullToRefreshGridView mPullRefreshListView;  
  5.     private ArrayAdapter<String> mAdapter;  
  6.   
  7.     private int mItemCount = 10;  
  8.   
  9.     @Override  
  10.     protected void onCreate(Bundle savedInstanceState)  
  11.     {  
  12.         super.onCreate(savedInstanceState);  
  13.         setContentView(R.layout.activity_ptr_grid);  
  14.         // 得到控件  
  15.         mPullRefreshListView = (PullToRefreshGridView) findViewById(R.id.pull_refresh_grid);  
  16.   
  17.         // 初始化數據和數據源  
  18.         initDatas();  
  19.   
  20.         mAdapter = new ArrayAdapter<String>(this, R.layout.grid_item,  
  21.                 R.id.id_grid_item_text, mListItems);  
  22.         mPullRefreshListView.setAdapter(mAdapter);  
  23.   
  24.         mPullRefreshListView  
  25.                 .setOnRefreshListener(new OnRefreshListener2<GridView>()  
  26.                 {  
  27.   
  28.                     @Override  
  29.                     public void onPullDownToRefresh(  
  30.                             PullToRefreshBase<GridView> refreshView)  
  31.                     {  
  32.                         Log.e("TAG""onPullDownToRefresh"); // Do work to  
  33.                         String label = DateUtils.formatDateTime(  
  34.                                 getApplicationContext(),  
  35.                                 System.currentTimeMillis(),  
  36.                                 DateUtils.FORMAT_SHOW_TIME  
  37.                                         | DateUtils.FORMAT_SHOW_DATE  
  38.                                         | DateUtils.FORMAT_ABBREV_ALL);  
  39.   
  40.                         // Update the LastUpdatedLabel  
  41.                         refreshView.getLoadingLayoutProxy()  
  42.                                 .setLastUpdatedLabel(label);  
  43.                           
  44.                         new GetDataTask().execute();  
  45.                     }  
  46.   
  47.                     @Override  
  48.                     public void onPullUpToRefresh(  
  49.                             PullToRefreshBase<GridView> refreshView)  
  50.                     {  
  51.                         Log.e("TAG""onPullUpToRefresh"); // Do work to refresh  
  52.                                                             // the list here.  
  53.                         new GetDataTask().execute();  
  54.                     }  
  55.                 });  
  56.     }  
  57.   
  58.     private void initDatas()  
  59.     {  
  60.         mListItems = new LinkedList<String>();  
  61.   
  62.         for (int i = 0; i < mItemCount; i++)  
  63.         {  
  64.             mListItems.add(i + "");  
  65.         }  
  66.     }  
  67.   
  68.     private class GetDataTask extends AsyncTask<Void, Void, Void>  
  69.     {  
  70.   
  71.         @Override  
  72.         protected Void doInBackground(Void... params)  
  73.         {  
  74.             try  
  75.             {  
  76.                 Thread.sleep(2000);  
  77.             } catch (InterruptedException e)  
  78.             {  
  79.             }  
  80.             return null;  
  81.         }  
  82.   
  83.         @Override  
  84.         protected void onPostExecute(Void result)  
  85.         {  
  86.             mListItems.add("" + mItemCount++);  
  87.             mAdapter.notifyDataSetChanged();  
  88.             // Call onRefreshComplete when the list has been refreshed.  
  89.             mPullRefreshListView.onRefreshComplete();  
  90.         }  
  91.     }  

基本上上例沒有任何區別,直接看效果圖吧:

效果還是不錯的,如果你比較細心會發現,那個下拉刷新的轉圈的圖片咋變成機器人了,那是因爲我在佈局文件裏面設置了:

[html] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. <com.handmark.pulltorefresh.library.PullToRefreshGridView  
  2.        ptr:ptrDrawable="@drawable/ic_launcher"  
  3.        ...  
  4.        />  

當然了這是旋轉的效果,一般常用的還有,一個箭頭倒置的效果,其實也很簡單,一個屬性:

ptr:ptrAnimationStyle="flip"

去掉 ptr:ptrDrawable="@drawable/ic_launcher"這個屬性,如果你希望用下圖默認的箭頭,你也可以自定義。

添加後,箭頭就是這個樣子:

ptr:ptrAnimationStyle的取值:flip(翻轉動畫), rotate(旋轉動畫) 。 

ptr:ptrDrawable則就是設置圖標了。


4、自定義下拉指示器文本內容等效果

可以在初始化完成mPullRefreshListView後,通過mPullRefreshListView.getLoadingLayoutProxy()可以得到一個ILoadingLayout對象,這個對象可以設置各種指示器中的樣式、文本等。

[java] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. ILoadingLayout startLabels = mPullRefreshListView  
  2.                 .getLoadingLayoutProxy();  
  3.         startLabels.setPullLabel("你可勁拉,拉...");// 剛下拉時,顯示的提示  
  4.         startLabels.setRefreshingLabel("好嘞,正在刷新...");// 刷新時  
  5.         startLabels.setReleaseLabel("你敢放,我就敢刷新...");// 下來達到一定距離時,顯示的提示  

如果你比較細心,會發現,前面我們設置上次刷新時間已經用到了:

// Update the LastUpdatedLabel
refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);

現在的效果是:



默認是上拉和下拉的字同時改變的,如果我希望單獨改變呢?

[java] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. private void initIndicator()  
  2.     {  
  3.         ILoadingLayout startLabels = mPullRefreshListView  
  4.                 .getLoadingLayoutProxy(truefalse);  
  5.         startLabels.setPullLabel("你可勁拉,拉...");// 剛下拉時,顯示的提示  
  6.         startLabels.setRefreshingLabel("好嘞,正在刷新...");// 刷新時  
  7.         startLabels.setReleaseLabel("你敢放,我就敢刷新...");// 下來達到一定距離時,顯示的提示  
  8.   
  9.         ILoadingLayout endLabels = mPullRefreshListView.getLoadingLayoutProxy(  
  10.                 falsetrue);  
  11.         endLabels.setPullLabel("你可勁拉,拉2...");// 剛下拉時,顯示的提示  
  12.         endLabels.setRefreshingLabel("好嘞,正在刷新2...");// 刷新時  
  13.         endLabels.setReleaseLabel("你敢放,我就敢刷新2...");// 下來達到一定距離時,顯示的提示  
  14.     }  

mPullRefreshListView.getLoadingLayoutProxy(true, false);接收兩個參數,爲true,false返回設置下拉的ILoadingLayout;爲false,true返回設置上拉的。

5、常用的一些屬性

當然了,pull-to-refresh在xml中還能定義一些屬性:

ptrMode,ptrDrawable,ptrAnimationStyle這三個上面已經介紹過。

ptrRefreshableViewBackground 設置整個mPullRefreshListView的背景色

ptrHeaderBackground 設置下拉Header或者上拉Footer的背景色

ptrHeaderTextColor 用於設置Header與Footer中文本的顏色

ptrHeaderSubTextColor 用於設置Header與Footer中上次刷新時間的顏色

ptrShowIndicator如果爲true會在mPullRefreshListView中出現icon,右上角和右下角,挺有意思的。

ptrHeaderTextAppearance , ptrSubHeaderTextAppearance分別設置拉Header或者上拉Footer中字體的類型顏色等等。

ptrRotateDrawableWhilePulling當動畫設置爲rotate時,下拉是是否旋轉。

ptrScrollingWhileRefreshingEnabled刷新的時候,是否允許ListView或GridView滾動。覺得爲true比較好。

ptrListViewExtrasEnabled 決定了Header,Footer以何種方式加入mPullRefreshListView,true爲headView方式加入,就是滾動時刷新頭部會一起滾動。

最後2個其實對於用戶體驗還是挺重要的,如果設置的時候考慮下~。其他的屬性自己選擇就好。

注:上述屬性很多都可以代碼控制,如果有需要可以直接mPullRefreshListView.set屬性名 查看

以上爲pull-to-refresh所有支持的屬性~~

定義了一堆的效果:


右上、右下那個圖標就是ptrShowIndicator。好了,大家可以按照自己的需求對着上面的屬性解釋配置。


在github上下載的例子,是依賴3個項目的,一個基本的library_pullToRefresh,一個PullToRefreshViewPager,一個PullToRefreshListFragment ;

上面介紹的例子只依賴library_pullToRefresh,其他兩個依賴不用導入。



好了,如果你覺得本篇博客對你有用,就點個贊~留個言吧


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章