项目主页:android-Ultra-Pull-To-Refresh
源码分析:android-Ultra-Pull-To-Refresh 源码解析
如何运用到项目中
- gradle中引入依赖:
1
compile 'in.srain.cube:ultra-ptr:1.0.10'
- 将需要可以下拉刷新的View用PtrFrameLayout控件包住,比如如下的xml配置:
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<in.srain.cube.views.ptr.PtrFrameLayout
android:id="@+id/store_house_ptr_frame"
xmlns:cube_ptr="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
cube_ptr:ptr_resistance="1.7"
cube_ptr:ptr_ratio_of_header_height_to_refresh="1.2"
cube_ptr:ptr_duration_to_close="300"
cube_ptr:ptr_duration_to_close_header="2000"
cube_ptr:ptr_keep_header_when_refresh="true"
cube_ptr:ptr_pull_to_fresh="false" >
<ImageView
android:id="@+id/ptr_image_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<LinearLayout
android:id="@+id/store_house_ptr_image_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/cube_mints_333333"
android:clickable="true"
android:padding="10dp">
</LinearLayout>
</in.srain.cube.views.ptr.PtrFrameLayout>
这里需要注意,PtrFrameLayout只能包含两个子View,第一个是下拉刷新相关的View,第二个则是业务相关的具体的View.
在代码中需要实现两个接口,PtrHandler接口和PtrUIHandler接口。
- PtrHandler接口代表下拉刷新的功能接口,包含刷新功能回调方法以及判断是否可以下拉的方法。
两个方法具体为:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16public interface PtrHandler {
/**
* Check can do refresh or not. For example the content is empty or the first child is in view.
* <p/>
* {@link in.srain.cube.views.ptr.PtrDefaultHandler#checkContentCanBePulledDown}
*/
public boolean checkCanDoRefresh(final PtrFrameLayout frame, final View content, final View header);
/**
* When refresh begin
*
* @param frame
*/
public void onRefreshBegin(final PtrFrameLayout frame);
}
作者已经帮我们实现了一个通用的Handler名为PtrDefaultHandler.一般情况下都可以使用,如果存在自定义的View则需要自己实现对应的checkCanDoRefresh方法。
- PtrUIHandler接口代表下拉刷新UI接口,是对下拉刷新UI变化的抽象。一般需要实现对应的5个方法:
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
28public interface PtrUIHandler {
/**
* When the content view has reached top and refresh has been completed, view will be reset.
*
* @param frame
*/
public void onUIReset(PtrFrameLayout frame);
/**
* prepare for loading
*
* @param frame
*/
public void onUIRefreshPrepare(PtrFrameLayout frame);
/**
* perform refreshing UI
*/
public void onUIRefreshBegin(PtrFrameLayout frame);
/**
* perform UI after refresh
*/
public void onUIRefreshComplete(PtrFrameLayout frame);
public void onUIPositionChange(PtrFrameLayout frame, boolean isUnderTouch, byte status, int oldPosition, int currentPosition, float oldPercent, float currentPercent);
}
我们在具体用的时候自己封装了下默认的PtrFrameLayout,比如成为PtrClassicFrameLayout,它自身已经带了一个默认的下拉刷新头部。
所以我们在自己的xml中只要在PtrClassicFrameLayout控件中包含自己的业务页面即可。并且实现PtrClassicFrameLayout的PtrHandler接口,由于含有默认的下拉刷新头部,故不需要实现PtrUIHandler接口。
具体的例子可以参考作者的demo。