SwipeRefreshLayout

我们就那网格布局例子为基础, 在它的?RecyclerView 上面加上一个?SwipeRefreshLayout 控件,这样要注意一下,SwipeRefreshLayout 必须是?RecyclerView 的父容器,也就是?SwipeRefreshLayout? 包裹 RecyclerView,看下面的代码你就非常清楚了:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.v4.widget.SwipeRefreshLayout
android:id="@+id/swipe_refresh"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.v7.widget.RecyclerView
android:id="@+id/grid_recy_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />

</android.support.v4.widget.SwipeRefreshLayout>

</RelativeLayout>
? ??SwipeRefreshLayout 要刷新的话,需要添加一个监听事件,又因为适配器在刷新后需要把数据也刷新一下,然后再绑定到?RecyclerView 上,代码如下所示。

swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
gridData.clear();
addGridData();
gridAdapter.notifyDataSetChanged();

new Handler().postDelayed(new Runnable() {
@Override
public void run() {
if (swipeRefreshLayout.isRefreshing()) {
swipeRefreshLayout.setRefreshing(false);
}
}
}, 1500);

}
});
? ? 首先,要把集合给清空,然后为集合添加新的数据,最后调用适配器通知一下重新绑定数据就搞定了。那么效果如下:

?这里有个与?SwipeRefreshLayout 相关的比较常用的属性,直接看下面的代码就知道了:

//为下拉刷新,设置一组颜色
swipeRefreshLayout.setColorSchemeColors(Color.BLUE, Color.RED, Color.GREEN);
//设置触发刷新的距离
swipeRefreshLayout.setDistanceToTriggerSync(200);
//设置滑动的距离
swipeRefreshLayout.setSlingshotDistance(400);
?刷新时就会不停的变化进度的颜色效果,显得花里胡哨的,当然了,你也可以只添加一种颜色。

还有两个用于设置刷新的监听与取消情况:

//开始刷新,false 取消刷新
swipeRefreshLayout.setRefreshing(true);
//判断是否正在刷新
swipeRefreshLayout.isRefreshing(http://www.amjmh.com/v/);
---------------------

原文地址:https://www.cnblogs.com/ly570/p/11347021.html