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

jopen 8年前發布 | 23K 次閱讀 Android開發 移動開發

轉載請標明出處: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>
我們添加了一個屬性:ptr:ptrMode="both" ,意思:上拉和下拉都支持。

可選值為: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>
PullToRefreshGridView 的item的布局文件:

<?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,其他兩個依賴不用導入。

 

 

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

 

源碼點擊下載

 

 

 

來自: http://blog.csdn.net//lmj623565791/article/details/38238749

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!