天天看點

下拉重新整理控件SwipeRefreshLayout用法簡介

以前需要下拉重新整理效果時,一般都自定義ListView,添加頭部視圖,實作下拉效果。SwipeRefreshLayout控件則省去的自定義頭部視圖的繁瑣,其用法非常簡單。先看一下界面布局檔案:
           
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

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

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

</LinearLayout>
           

通過布局檔案可知,使用SwipeRefreshLayout控件需要導入v4包。在布局檔案中,隻要将清單控件直接包含在SwipeRefreshLayout中即可。

在Java檔案中,主要程式如下:

swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
		swipeRefreshLayout.setColorScheme(android.R.color.white,
				android.R.color.holo_green_light,
				android.R.color.holo_orange_light,
				android.R.color.holo_red_light);

		swipeRefreshLayout.setOnRefreshListener(new OnRefreshListener() {

			@Override
			public void onRefresh() {
				// TODO Auto-generated method stub
				new Handler().postDelayed(new Runnable() {
					public void run() {
						swipeRefreshLayout.setRefreshing(false);
						arrayList.add(0, "---->" + ++f);
						adapter.notifyDataSetChanged();
					}
				}, 2000);
			}
		});
           

這裡主要需要注意兩個地方:一是swipeRefreshLayout.setColorScheme(),該方法是設定重新整理效果的顔色,最多同時支援4種顔色。二是使用swipeRefreshLayout控件需為其注冊OnRefreshListener()監聽,監聽重新整理操作,并重寫onRefresh()方法。在onRefresh()方法中,可以設定重新整理的具體操作,例如添加新資料、重新整理效果持續時間等等。

以上就是SwipeRefreshLayout控件的用法,很簡單。因程式中的其他代碼非常簡單,就不再貼出來。大家有可以下載下傳Demo看看。連結在最後給出。

Demo:SwipeRefreshLayout