1. 程式人生 > >SwipeRefreshLayout實現下拉重新整理功能

SwipeRefreshLayout實現下拉重新整理功能

在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的動作停止並且隱藏。