轉載請標明出處: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.
佈局文件:
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent" >
- <com.handmark.pulltorefresh.library.PullToRefreshListView
- xmlns:ptr="http://schemas.android.com/apk/res-auto"
- android:id="@+id/pull_refresh_list"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:cacheColorHint="#00000000"
- android:divider="#19000000"
- android:dividerHeight="4dp"
- android:fadingEdge="none"
- android:fastScrollEnabled="false"
- android:footerDividersEnabled="false"
- android:headerDividersEnabled="false"
- android:smoothScrollbar="true" >
- </com.handmark.pulltorefresh.library.PullToRefreshListView>
- </RelativeLayout>
聲明瞭一個PullToRefreshListView,裏面所有的屬性都是ListView的,沒有任何其他屬性,當然了PullToRefreshListView也提供了很多配置的屬性,後面會詳細介紹。
Activity的代碼:
- package com.example.zhy_pulltorefreash_chenyoca;
- import java.util.LinkedList;
- import android.app.Activity;
- import android.os.AsyncTask;
- import android.os.Bundle;
- import android.text.format.DateUtils;
- import android.widget.ArrayAdapter;
- import android.widget.ListView;
- import com.handmark.pulltorefresh.library.PullToRefreshBase;
- import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
- import com.handmark.pulltorefresh.library.PullToRefreshListView;
- public class PullToRefreshListActivity extends Activity
- {
- private LinkedList<String> mListItems;
- /**
- * 上拉刷新的控件
- */
- private PullToRefreshListView mPullRefreshListView;
- private ArrayAdapter<String> mAdapter;
- private int mItemCount = 9;
- @Override
- protected void onCreate(Bundle savedInstanceState)
- {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- // 得到控件
- mPullRefreshListView = (PullToRefreshListView) findViewById(R.id.pull_refresh_list);
- //初始化數據
- initDatas();
- //設置適配器
- mAdapter = new ArrayAdapter<String>(this,
- android.R.layout.simple_list_item_1, mListItems);
- mPullRefreshListView.setAdapter(mAdapter);
- // 設置監聽事件
- mPullRefreshListView
- .setOnRefreshListener(new OnRefreshListener<ListView>()
- {
- @Override
- public void onRefresh(
- PullToRefreshBase<ListView> refreshView)
- {
- String label = DateUtils.formatDateTime(
- getApplicationContext(),
- System.currentTimeMillis(),
- DateUtils.FORMAT_SHOW_TIME
- | DateUtils.FORMAT_SHOW_DATE
- | DateUtils.FORMAT_ABBREV_ALL);
- // 顯示最後更新的時間
- refreshView.getLoadingLayoutProxy()
- .setLastUpdatedLabel(label);
- // 模擬加載任務
- new GetDataTask().execute();
- }
- });
- }
- private void initDatas()
- {
- // 初始化數據和數據源
- mListItems = new LinkedList<String>();
- for (int i = 0; i < mItemCount; i++)
- {
- mListItems.add("" + i);
- }
- }
- private class GetDataTask extends AsyncTask<Void, Void, String>
- {
- @Override
- protected String doInBackground(Void... params)
- {
- try
- {
- Thread.sleep(2000);
- } catch (InterruptedException e)
- {
- }
- return "" + (mItemCount++);
- }
- @Override
- protected void onPostExecute(String result)
- {
- mListItems.add(result);
- mAdapter.notifyDataSetChanged();
- // Call onRefreshComplete when the list has been refreshed.
- mPullRefreshListView.onRefreshComplete();
- }
- }
- }
代碼極其簡單,得到PullToRefreshListView控件,然後像ListView一樣設置數據集。當然了,我們有下拉刷新,所以必須設置下拉刷新的回調:
setOnRefreshListener(new OnRefreshListener<ListView>(){}
我們在回調中模擬了一個異步任務,加載了一個Item。
效果圖:
下拉時,執行我們的GetDataTask任務,任務執行完成後在onPostExecute中 調用mPullRefreshListView.onRefreshComplete();完成刷新。
是不是分分鐘實現下拉刷新。當然了,你可能會有疑問,下拉刷新的指示器上的文字可以自定義嗎?那個圖片可以換成箭頭嗎?說好的上拉加載更多呢?後面會一一添加~
2、添加上拉加載更多
如過希望實現上拉加載更多,那麼首先需要在佈局文件的聲明屬性中添加一個屬性,用於指定目前的下拉模式:
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent" >
- <com.handmark.pulltorefresh.library.PullToRefreshListView
- xmlns:ptr="http://schemas.android.com/apk/res-auto"
- android:id="@+id/pull_refresh_list"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:cacheColorHint="#00000000"
- android:divider="#19000000"
- android:dividerHeight="4dp"
- android:fadingEdge="none"
- android:fastScrollEnabled="false"
- android:footerDividersEnabled="false"
- android:headerDividersEnabled="false"
- android:smoothScrollbar="true"
- ptr:ptrMode="both" >
- </com.handmark.pulltorefresh.library.PullToRefreshListView>
- </RelativeLayout>
可選值爲:disabled(禁用下拉刷新),pullFromStart(僅支持下拉刷新),pullFromEnd(僅支持上拉刷新),both(二者都支持),manualOnly(只允許手動觸發)
當然了,如果你不喜歡在佈局文件中指定,完全可以使用代碼設置,在onCreate裏面寫:mPullRefreshListView.setMode(Mode.BOTH);//設置你需要的模式
設置了模式爲雙向都支持,當然必須爲上拉和下拉分別設置回調,請看下面的代碼:
- package com.example.zhy_pulltorefreash_chenyoca;
- import java.util.LinkedList;
- import android.app.Activity;
- import android.os.AsyncTask;
- import android.os.Bundle;
- import android.text.format.DateUtils;
- import android.util.Log;
- import android.widget.ArrayAdapter;
- import android.widget.ListView;
- import com.handmark.pulltorefresh.library.PullToRefreshBase;
- import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
- import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
- import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
- import com.handmark.pulltorefresh.library.PullToRefreshListView;
- public class PullToRefreshListActivity extends Activity
- {
- private LinkedList<String> mListItems;
- /**
- * 上拉刷新的控件
- */
- private PullToRefreshListView mPullRefreshListView;
- private ArrayAdapter<String> mAdapter;
- private int mItemCount = 9;
- @Override
- protected void onCreate(Bundle savedInstanceState)
- {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- // 得到控件
- mPullRefreshListView = (PullToRefreshListView) findViewById(R.id.pull_refresh_list);
- mPullRefreshListView.setMode(Mode.BOTH);
- // 初始化數據
- initDatas();
- // 設置適配器
- mAdapter = new ArrayAdapter<String>(this,
- android.R.layout.simple_list_item_1, mListItems);
- mPullRefreshListView.setAdapter(mAdapter);
- mPullRefreshListView
- .setOnRefreshListener(new OnRefreshListener2<ListView>()
- {
- @Override
- public void onPullDownToRefresh(
- PullToRefreshBase<ListView> refreshView)
- {
- Log.e("TAG", "onPullDownToRefresh");
- //這裏寫下拉刷新的任務
- new GetDataTask().execute();
- }
- @Override
- public void onPullUpToRefresh(
- PullToRefreshBase<ListView> refreshView)
- {
- Log.e("TAG", "onPullUpToRefresh");
- //這裏寫上拉加載更多的任務
- new GetDataTask().execute();
- }
- });
- }
- private void initDatas()
- {
- // 初始化數據和數據源
- mListItems = new LinkedList<String>();
- for (int i = 0; i < mItemCount; i++)
- {
- mListItems.add("" + i);
- }
- }
- private class GetDataTask extends AsyncTask<Void, Void, String>
- {
- @Override
- protected String doInBackground(Void... params)
- {
- try
- {
- Thread.sleep(2000);
- } catch (InterruptedException e)
- {
- }
- return "" + (mItemCount++);
- }
- @Override
- protected void onPostExecute(String result)
- {
- mListItems.add(result);
- mAdapter.notifyDataSetChanged();
- // Call onRefreshComplete when the list has been refreshed.
- mPullRefreshListView.onRefreshComplete();
- }
- }
和第一段的代碼只有一個地方有區別,可能很難發現:
mPullRefreshListView.setOnRefreshListener(new OnRefreshListener2<ListView>(){});注意這裏的接口類型是OnRefreshListener2,多了個2,和上面的不一樣,這個接口包含兩個方法,一個上拉回調,一個下拉回調。好了,這樣我們就成功添加了上拉與下拉,並且分別可以控制其回調代碼。
效果圖:
咋樣,是不是也很簡單~注:如果你的上拉和下拉需求是執行一樣的代碼,那麼你可以繼續註冊OnRefreshListener接口,上拉和下拉都會執行同一個方法。
接下來介紹如何使用帶下拉刷新和加載更多的的GridView和自定義樣式~
3、帶下拉和上拉的GridView ( PullToRefreshGridView )
同樣的pull-to-refresh把GridView封裝爲:PullToRefreshGridView 。用法和PullToRefreshListView一摸一樣~
首先看主佈局文件:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical" >
- <!-- The PullToRefreshGridView replaces a standard GridView widget. -->
- <com.handmark.pulltorefresh.library.PullToRefreshGridView
- xmlns:ptr="http://schemas.android.com/apk/res-auto"
- android:id="@+id/pull_refresh_grid"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:columnWidth="100dp"
- android:gravity="center_horizontal"
- android:horizontalSpacing="1dp"
- android:numColumns="auto_fit"
- android:stretchMode="columnWidth"
- android:verticalSpacing="1dp"
- ptr:ptrDrawable="@drawable/ic_launcher"
- ptr:ptrMode="both" />
- </LinearLayout>
- <?xml version="1.0" encoding="utf-8"?>
- <TextView xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/id_grid_item_text"
- android:layout_width="100dp"
- android:gravity="center"
- android:textColor="#ffffff"
- android:textSize="16sp"
- android:background="#000000"
- android:layout_height="100dp" />
接下來就是Activity的代碼了:
- public class PullToRefreshGridActivity extends Activity
- {
- private LinkedList<String> mListItems;
- private PullToRefreshGridView mPullRefreshListView;
- private ArrayAdapter<String> mAdapter;
- private int mItemCount = 10;
- @Override
- protected void onCreate(Bundle savedInstanceState)
- {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_ptr_grid);
- // 得到控件
- mPullRefreshListView = (PullToRefreshGridView) findViewById(R.id.pull_refresh_grid);
- // 初始化數據和數據源
- initDatas();
- mAdapter = new ArrayAdapter<String>(this, R.layout.grid_item,
- R.id.id_grid_item_text, mListItems);
- mPullRefreshListView.setAdapter(mAdapter);
- mPullRefreshListView
- .setOnRefreshListener(new OnRefreshListener2<GridView>()
- {
- @Override
- public void onPullDownToRefresh(
- PullToRefreshBase<GridView> refreshView)
- {
- Log.e("TAG", "onPullDownToRefresh"); // Do work to
- String label = DateUtils.formatDateTime(
- getApplicationContext(),
- System.currentTimeMillis(),
- DateUtils.FORMAT_SHOW_TIME
- | DateUtils.FORMAT_SHOW_DATE
- | DateUtils.FORMAT_ABBREV_ALL);
- // Update the LastUpdatedLabel
- refreshView.getLoadingLayoutProxy()
- .setLastUpdatedLabel(label);
- new GetDataTask().execute();
- }
- @Override
- public void onPullUpToRefresh(
- PullToRefreshBase<GridView> refreshView)
- {
- Log.e("TAG", "onPullUpToRefresh"); // Do work to refresh
- // the list here.
- new GetDataTask().execute();
- }
- });
- }
- private void initDatas()
- {
- mListItems = new LinkedList<String>();
- for (int i = 0; i < mItemCount; i++)
- {
- mListItems.add(i + "");
- }
- }
- private class GetDataTask extends AsyncTask<Void, Void, Void>
- {
- @Override
- protected Void doInBackground(Void... params)
- {
- try
- {
- Thread.sleep(2000);
- } catch (InterruptedException e)
- {
- }
- return null;
- }
- @Override
- protected void onPostExecute(Void result)
- {
- mListItems.add("" + mItemCount++);
- mAdapter.notifyDataSetChanged();
- // Call onRefreshComplete when the list has been refreshed.
- mPullRefreshListView.onRefreshComplete();
- }
- }
基本上上例沒有任何區別,直接看效果圖吧:
效果還是不錯的,如果你比較細心會發現,那個下拉刷新的轉圈的圖片咋變成機器人了,那是因爲我在佈局文件裏面設置了:
- <com.handmark.pulltorefresh.library.PullToRefreshGridView
- ptr:ptrDrawable="@drawable/ic_launcher"
- ...
- />
當然了這是旋轉的效果,一般常用的還有,一個箭頭倒置的效果,其實也很簡單,一個屬性:
ptr:ptrAnimationStyle="flip"
去掉 ptr:ptrDrawable="@drawable/ic_launcher"這個屬性,如果你希望用下圖默認的箭頭,你也可以自定義。
添加後,箭頭就是這個樣子:
ptr:ptrAnimationStyle的取值:flip(翻轉動畫), rotate(旋轉動畫) 。
ptr:ptrDrawable則就是設置圖標了。
4、自定義下拉指示器文本內容等效果
可以在初始化完成mPullRefreshListView後,通過mPullRefreshListView.getLoadingLayoutProxy()可以得到一個ILoadingLayout對象,這個對象可以設置各種指示器中的樣式、文本等。
- ILoadingLayout startLabels = mPullRefreshListView
- .getLoadingLayoutProxy();
- startLabels.setPullLabel("你可勁拉,拉...");// 剛下拉時,顯示的提示
- startLabels.setRefreshingLabel("好嘞,正在刷新...");// 刷新時
- startLabels.setReleaseLabel("你敢放,我就敢刷新...");// 下來達到一定距離時,顯示的提示
如果你比較細心,會發現,前面我們設置上次刷新時間已經用到了:
// Update the LastUpdatedLabel
refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
現在的效果是:
默認是上拉和下拉的字同時改變的,如果我希望單獨改變呢?
- private void initIndicator()
- {
- ILoadingLayout startLabels = mPullRefreshListView
- .getLoadingLayoutProxy(true, false);
- startLabels.setPullLabel("你可勁拉,拉...");// 剛下拉時,顯示的提示
- startLabels.setRefreshingLabel("好嘞,正在刷新...");// 刷新時
- startLabels.setReleaseLabel("你敢放,我就敢刷新...");// 下來達到一定距離時,顯示的提示
- ILoadingLayout endLabels = mPullRefreshListView.getLoadingLayoutProxy(
- false, true);
- endLabels.setPullLabel("你可勁拉,拉2...");// 剛下拉時,顯示的提示
- endLabels.setRefreshingLabel("好嘞,正在刷新2...");// 刷新時
- endLabels.setReleaseLabel("你敢放,我就敢刷新2...");// 下來達到一定距離時,顯示的提示
- }
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,其他兩個依賴不用導入。
好了,如果你覺得本篇博客對你有用,就點個贊~留個言吧