群里一哥们今天聊天偶然提到这个git hub上的控件:pull-to-refresh ,有兴趣的看下,样例中的功能极其强大,支持非常多控件。本篇博客具体给大家介绍下ListView和GridView利用pull-to-rerfesh 实现下拉刷新和上拉载入很多其它。对布局不清楚的能够看Android研究自己定义ViewGroup实现FlowLayout
具体解释

1、ListView下拉刷新高速入门

pull-to-refresh对ListView进行了封装,叫做:PullToRefreshListView,使用方法和listview没什么差别,以下看demo.

布局文件:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<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的代码:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
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、加入上拉载入很多其它

如过希望实现上拉载入很多其它,那么首先须要在布局文件的声明属性中加入一个属性,用于指定眼下的下拉模式:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<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);//设置你须要的模式

设置了模式为双向都支持,当然必须为上拉和下拉分别设置回调,请看以下的代码:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
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,和上面的不一样,这个接口包括两个方法,一个上拉回调,一个下拉回调。好了,这样我们就成功加入了上拉与下拉,而且分别能够控制其回调代码。

效果图:

咋样,是不是也非常easy~注:假设你的上拉和下拉需求是运行一样的代码,那么你能够继续注冊OnRefreshListener接口,上拉和下拉都会运行同一个方法。

接下来介绍怎样使用带下拉刷新和载入很多其它的的GridView和自己定义样式~

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

相同的pull-to-refresh把GridView封装为:PullToRefreshGridView 。使用方法和PullToRefreshListView一摸一样~

首先看主布局文件:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?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" />
1
2
3
4
5
6
7
8
9
<?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的代码了:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
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();
        }
    }

基本上上例没有不论什么差别,直接看效果图吧:

效果还是不错的,假设你比較细心会发现,那个下拉刷新的转圈的图片咋变成机器人了,那是由于我在布局文件中面设置了:


1
2
3
4
<com.handmark.pulltorefresh.library.PullToRefreshGridView
        ptr:ptrDrawable="@drawable/ic_launcher"
        ...
        />

当然了这是旋转的效果,一般经常使用的还有,一个箭头倒置的效果,事实上也非常easy,一个属性:

ptr:ptrAnimationStyle=”flip”

去掉 ptr:ptrDrawable=”@drawable/ic_launcher”这个属性,假设你希望用下图默认的箭头,你也能够自己定义。

加入后,箭头就是这个样子:

ptr:ptrAnimationStyle的取值:flip(翻转动画), rotate(旋转动画) 。

ptr:ptrDrawable则就是设置图标了。

4、自己定义下拉指示器文本内容等效果

能够在初始化完毕mPullRefreshListView后,通过mPullRefreshListView.getLoadingLayoutProxy()能够得到一个ILoadingLayout对象,这个对象能够设置各种指示器中的样式、文本等。


1
2
3
4
5
ILoadingLayout
startLabels =
mPullRefreshListView
                .getLoadingLayoutProxy();
        startLabels.setPullLabel("你可劲拉,拉...");//
刚下拉时,显示的提示
        startLabels.setRefreshingLabel("好嘞,正在刷新...");//
刷新时
        startLabels.setReleaseLabel("你敢放,我就敢刷新...");//
下来达到一定距离时,显示的提示

假设你比較细心,会发现,前面我们设置上次刷新时间已经用到了:

// Update the LastUpdatedLabel

refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);

如今的效果是:

默认是上拉和下拉的字同一时候改变的,假设我希望单独改变呢?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
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,其它两个依赖不用导入。

好了,假设你认为本篇博客对你实用,就点个赞~留个言吧

源代码下载:zhy_pulltorefreash_chenyoca

最新文章

  1. 初学JavaScript
  2. Javascript外部对象
  3. 微信支付之JSAPI开发第一篇-基本概念
  4. hdu 4049 2011北京赛区网络赛J 状压dp ***
  5. 提高网站性能的 5 个 Grunt任务//////////////////z
  6. 项目管理软件kanboard安装
  7. 一个简单的Spring测试的例子
  8. C#数据等待
  9. 【转】iOS开发常用的第三方类库
  10. dump iot表
  11. 【转】OpenGL基础图形编程(一)
  12. APP迁移
  13. perl的一些基本用法
  14. WORK
  15. 埋锅。。。BZOJ1004-置换群+burnside定理+
  16. linux 获取帮助的命令
  17. JS的事件流的概念(重点)
  18. 代码的重构(Refactor-Extract)
  19. 在android中实现webview与javascript之间的交互(转)
  20. 在IIS上SSL的部署和启动SSL安全【转】

热门文章

  1. [IDEs]Eclipse自动格式化代码
  2. Python -- 堆数据结构 heapq - I love this game! - 博客频道 - CSDN.NET
  3. IOS开发之----四舍五入问题
  4. OpenRisc-32-ORPSoC烧写外部spi flash
  5. Linux下的softlink和hardlink(转)
  6. A Game of Thrones(16) - Edard
  7. document.write()相关
  8. poj1860(spfa判正环)
  9. Python – Get Object’s Class Name | Ridge Solutions, Ireland
  10. JS数组追加数组採用push.apply的坑