最近項目中需要用到ListView下拉重新整理的功能,一開始想圖省事,在網上直接找一個現成的,可是嘗試了 網上多個版本的下拉重新整理之後發現效果都不怎麼理想。有些是因為功能不完整或有Bug,有些是因為使用起來 太複雜,十全十美的還真沒找到。因此我也是放棄了在網上找現成代碼的想法,自己花功夫編寫了一種非常 簡單的下拉重新整理實現方案,現在拿出來和大家分享一下。相信在閱讀完本篇文章之後,大家都可以在自己的 項目中一分鐘引入下拉重新整理功能。
首先講一下實現原理。這裡我們將採取的方案是使用組合View的方 式,先自訂一個布局繼承自LinearLayout,然後在這個布局中加入下拉頭和ListView這兩個子項目,並讓 這兩個子項目縱向排列。初始化的時候,讓下拉頭向上位移出螢幕,這樣我們看到的就只有ListView了。然 後對ListView的touch事件進行監聽,如果當前ListView已經滾動到頂部並且手指還在向下拉的話,那就將下 拉頭顯示出來,鬆手後進行重新整理操作,並將下拉頭隱藏。原理示意圖如下:
那我們現在就來動 手實現一下,建立一個項目起名叫PullToRefreshTest,先在項目中定義一個下拉頭的布局檔案 pull_to_refresh.xml,代碼如下所示:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/pull_to_refresh_head" android:layout_width="fill_parent" android:layout_height="60dip" > <LinearLayout android:layout_width="200dip" android:layout_height="60dip" android:layout_centerInParent="true" android:orientation="horizontal" > <RelativeLayout android:layout_width="0dip" android:layout_height="60dip" android:layout_weight="3" > <ImageView android:id="@+id/arrow" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:src="@drawable/arrow" /> <ProgressBar android:id="@+id/progress_bar" android:layout_width="30dip" android:layout_height="30dip" android:layout_centerInParent="true" android:visibility="gone" /> </RelativeLayout> <LinearLayout android:layout_width="0dip" android:layout_height="60dip" android:layout_weight="12" android:orientation="vertical" > <TextView android:id="@+id/description" android:layout_width="fill_parent" android:layout_height="0dip" android:layout_weight="1" android:gravity="center_horizontal|bottom" android:text="@string/pull_to_refresh" /> <TextView android:id="@+id/updated_at" android:layout_width="fill_parent" android:layout_height="0dip" android:layout_weight="1" android:gravity="center_horizontal|top" android:text="@string/updated_at" /> </LinearLayout> </LinearLayout> </RelativeLayout>
查看本欄目更多精彩內容:http://www.bianceng.cnhttp://www.bianceng.cn/OS/extra/