在Android5.0的v4包中,Google提供了SwipeRefreshLayout控件,用来执行下拉刷新的效果。
XML:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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">
<android.support.v4.widget.SwipeRefreshLayout
android:id="@+id/refresh_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"> //刷新控件,继承ViewGroup
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/layout_background">
<android.support.v4.widget.NestedScrollView
android:id="@+id/nested_scroll_view"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="@dimen/activity_margin_quarter"
android:layout_marginTop="@dimen/activity_margin_quarter"
android:fadeScrollbars="false"
android:nestedScrollingEnabled="false"
android:scrollbars="vertical"
android:visibility="visible"
tools:listitem="@layout/item_article_layout" />
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
</FrameLayout>
</android.support.v4.widget.SwipeRefreshLayout>
</android.support.design.widget.CoordinatorLayout>
这是一个完整的页面的XML,我们看到SwipeRefreshLayout是作为父控件,把内容全部包裹起来的。即便是包含了NestedScrollView和RecycleView,但是并不会引起滑动冲突,因为只有在滑动到最顶部并且下来动作足够明显的时候,才能触发SwipeRefreshLayout的刷新动作。
Java代码:
refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
currentPage = INDEX;
presenter.getArticles(currentPage,true,true); //下拉刷新最新的内容
}
});
这里实现OnRefreshListener()接口,监听刷新的动作,并且做我们业务需要做的事情。这里我们获取第一页的最新数据。
refreshLayout.post(new Runnable() {
@Override
public void run() {
refreshLayout.setRefreshing(isloding); //停止并隐藏刷新图标
}
});
这里需要注意,我们在下拉刷新的时候,是有一个loading的圆圈在转动的,因此在执行完刷新动作或者出错异常的时候,都需要把loading的动作停止并且隐藏。