SwipeRefreshLayout
SwipeRefreshLayout是官方提供的下拉刷新解决控件,具有使用简单,灵活等特点。不足的地方,不可以自定义刷新的头部和加载更多功能。不过通过修改SwipeRefreshLayout可以轻松实现这些功能,本文只介绍使用和对各个进行说明。
基本使用
在xml添加引入SwipeRefreshLayout的代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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"
tools:context=".MainActivity">
<android.support.v4.widget.SwipeRefreshLayout
android:id="@+id/refreshLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!">
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</android.support.v4.widget.SwipeRefreshLayout>
</LinearLayout>
然后在MainActivy设置,下拉刷新的回调即可
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
//模拟网络请求需要3000毫秒,请求完成,设置setRefreshing 为false
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
mSwipeRefreshLayout.setRefreshing(false);
}
}, 3000);
}
});
进阶
SwipeRefreshLayout 还提供了一些方法设置进度的样式,滑动的开始位置和结束位置等
方法名 | 作用 |
---|---|
setSize(int size) | 设置进度View样式的大小,只有两个值DEFAULT和LARGE |
setProgressViewOffset(boolean scale, int start, int end) | 设置进度View下拉的起始点和结束点,scale 是指设置是否需要放大或者缩小动画 |
setProgressViewEndTarget(boolean scale, int end) | 设置进度View下拉的结束点,scale 是指设置是否需要放大或者缩小动画 |
setColorSchemeColors(@ColorInt int… colors) } | 设置进度View的组合颜色,在手指上下滑时使用第一个颜色,在刷新中,会一个个颜色进行切换 |
setDistanceToTriggerSync(int distance) | 设置触发刷新的距离 |
setOnChildScrollUpCallback(@Nullable OnChildScrollUpCallback callback)k | 如果child是自己自定义的view,可以通过这个回调,告诉swipeRefreshLayoutchild是否可以滑动 |
用法使用举例
//设置进度View样式的大小,只有两个值DEFAULT和LARGE
mSwipeRefreshLayout.setSize(mSetSizeBean.size);
//设置进度View下拉的起始点和结束点,scale 是指设置是否需要放大或者缩小动画
mSwipeRefreshLayout.setProgressViewOffset(true, -0, 100);
//设置进度View下拉的结束点,scale 是指设置是否需要放大或者缩小动画
mSwipeRefreshLayout.setProgressViewEndTarget(true, 180);
//设置进度View的组合颜色,在手指上下滑时使用第一个颜色,在刷新中,会一个个颜色进行切换
mSwipeRefreshLayout.setColorSchemeColors(Color.BLACK, Color.GREEN, Color.RED, Color.YELLOW, Color.BLUE);
//设置触发刷新的距离
mSwipeRefreshLayout.setDistanceToTriggerSync(200);
//如果child是自己自定义的view,可以通过这个回调,告诉mSwipeRefreshLayoutchild是否可以滑动
mSwipeRefreshLayout.setOnChildScrollUpCallback(null);
实际效果代码链接
https://github.com/etwge/PracticeExample/tree/master/SwipeRefreshLayoutDemo
代码效果如下