转载请注明出处:http://blog.csdn.net/guolin_blog/article/details/9255575
最近项目中需要用到ListView下拉刷新的功能,一开始想图省事,在网上直接找一个现成的,可是尝试了网上多个版本的下拉刷新之后发现效果都不怎么理想。有些是因为功能不完整或有Bug,有些是因为使用起来太复杂,十全十美的还真没找到。因此我也是放弃了在网上找现成代码的想法,自己花功夫编写了一种非常简单的下拉刷新实现方案,现在拿出来和大家分享一下。相信在阅读完本篇文章之后,大家都可以在自己的项目中一分钟引入下拉刷新功能。
首先讲一下实现原理。这里我们将采取的方案是使用组合View的方式,先自定义一个布局继承自LinearLayout,然后在这个布局中加入下拉头和ListView这两个子元素,并让这两个子元素纵向排列。初始化的时候,让下拉头向上偏移出屏幕,这样我们看到的就只有ListView了。然后对ListView的touch事件进行监听,如果当前ListView已经滚动到顶部并且手指还在向下拉的话,那就将下拉头显示出来,松手后进行刷新操作,并将下拉头隐藏。原理示意图如下:
那我们现在就来动手实现一下,新建一个项目起名叫PullToRefreshTest,先在项目中定义一个下拉头的布局文件pull_to_refresh.xml,代码如下所示:
[html] view plaincopy
- <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>
在这个布局中,我们包含了一个下拉指示箭头,一个下拉状态文字提示,和一个上次更新的时间。当然,还有一个隐藏的旋转进度条,只有正在刷新的时候我们才会将它显示出来。
布局中所有引用的字符串我们都放在strings.xml中,如下所示:
[html] view plaincopy
- <?xml.relpost{clear:both}
Tag:
Freenovo 发表于2013-08-19 21:03:00 | 编辑 | 分享 0
引用地址: