一、效果演示
ListView实现下拉刷新,是很常见的功能。下面是一个模拟的效果,如下图:
效果说明:当往下拉ListView的时候,顶部就会有一个“下拉刷新”的标识被拉 出来,再往下拉的时候,标识就会变成”松开刷新“,期间还伴随一个箭头的变化。此时松开手指,则会变成进度条提示正在刷新,刷新完成后,则加载进来刷新的数据。如此反复,就是下拉刷新的功能。
二、准备Demo
其实本质上,ListView实现下拉刷新和实现分页加载都是一样的,都是一个自定义的ListView而已。甚至可以说,原理基本相同,只不过下拉刷新头布局变化相对分页加载复杂一点。
因此,我们仍旧使用《listView实现分页加载》里面的Demo,即首先搭建一个正常下的ListView,准备点模拟的数据。可以点击下面的链接,查看Demo的编写:
http://www.cnblogs.com/fuly550871915/p/4866929.html
三、实现头布局
好了,模拟的东西都准备完成了。下面我们首先编写头布局。比较简单,就是一个箭头,进度条好文本而已。命名为header.xml。代码如下:
<?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="horizontal"
android:gravity="center"> <ProgressBar
android:id="@+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
style="?android:attr/progressBarStyleSmall"/>
<ImageView
android:id="@+id/img_arrow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/down_arrow"/>
<TextView
android:id="@+id/textinfo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="5dp"
android:textSize="20dp"
android:text="下拉刷新"/> </LinearLayout>
然后,我们就开始自定义ListView吧。新建类MyListView,继承自ListView。在这里加上头布局即可。代码如下:
package com.fuly.load; import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ListView; public class MyListView extends ListView{ private View header;//头布局 //三个构造方法都要重写
public MyListView(Context context) {
super(context);
initView( context); }
public MyListView(Context context, AttributeSet attrs) {
super(context, attrs);
initView( context); }
public MyListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initView( context); } public void initView(Context context){ header = LayoutInflater.from(context).inflate(R.layout.header, null); //将头布局加进去
this.addHeaderView(header);
} }
自定义的ListView已经准备好了,下面就替换吧。修改activity_main.xml里的代码即可,如下:
<LinearLayout 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:background="#ccffff"> <com.fuly.load.MyListView
android:id= "@+id/list_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:dividerHeight="5dp"
android:divider="#00cc00"></com.fuly.load.MyListView>
</LinearLayout>
至此,我们已经把带头布局的ListView做好了。运行一下程序,会发现就是效果图的第一张。
那么,怎么来隐藏头布局呢?这并不简单,是下一节要详细说的内容。