如何使用下拉更新(SwipeRefreshLayout)

如何使用下拉更新(SwipeRefreshLayout)

情境

現在要使用下拉更新, 其實很方便,
google推出的下拉更新, 讓你在操作上更有彈性。

程式碼說明

新建立一個專案, 修改xml

<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:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/refresh_layout">
        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <TextView android:text="@string/hello_world"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
        </ScrollView>
    </android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>

**會發現裡面要包一個ScrollView不然無法捲動,
或者內部要包一個可以滑動的View(eg. ListView)。**

接著主程式

public class MainActivity extends Activity {

    private SwipeRefreshLayout mSwipeRefreshLayout;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.refresh_layout);
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mSwipeRefreshLayout.setRefreshing(false);
            }
        });

    }
}

註冊OnRefreshListener並且覆寫SwipeRefreshLayout的onRefresh方法,
當下滑到手指放開, 則會進行更新, 更新完畢後, 則將loading icon關閉。

程式碼