Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 下拉刷新 ListView 的原理與實現代碼

編輯:關於 Android 程式設計

下拉刷新已經成為移動應用的標配交互。仔細觀察可以發現,下拉刷新列表與普通列表的區別在於:當滾動條位於頂端時,如果繼續往下拉動,就會把整個列表拉下來,並顯示「鬆開刷新」的提示。

由此不難推導出實現思路:只需繼承 ListView 並重寫 onTouchEvent 即可;同時為了能在 XML 布局文件中引用,還需要一個參數為 Context、AttributeSet 的構造函數。

表面上的功能大概就這些。另一方面,刷新的行為本身也需要定義:刷新前做什麼、刷新時做什麼、刷新完成後做什麼。可以把這些行為抽象到一個接口中,再讓組件去實現。

整個組件的核心自然是 onTouchEvent 部分。這裡需要說明的是:在 ListView 中,數據的滾動與 ListView.scrollTo 的行為並不相同——數據的滾動是適配器層面的事。因此在不滿足下拉整個列表的條件下,onTouchEvent 應該返回 super.onTouchEvent(ev),交給 ListView 原本的處理邏輯。

考慮到組件的 id 和表頭布局需要事先定義,同時希望把這個組件復用於多個項目,於是將它作為一個 Library 來實現。下面是具體的實現代碼。

首先看表頭的布局文件 chenzong_push_refresh_header.xml:

復制代碼 代碼如下:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="40dip"
       >
    <ImageView
        android:layout_width="30dip"
        android:layout_height="40dip"
        android:background="@drawable/arrow_down"
           android:layout_alignParentLeft="true"
        android:id="@+id/push_refresh_header_img"
        android:layout_marginLeft="10dip"
        />
    <ProgressBar
        android:layout_width="40dip"
        android:layout_height="40dip"
        android:layout_alignParentLeft="true"
        android:layout_marginLeft="10dip"
        android:id="@+id/push_refresh_header_pb"
        android:visibility="gone"/>
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:orientation="vertical"
        >
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="最近一次更新在:"
            android:textColor="#000000"
            />
        <TextView
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:id="@+id/push_refresh_header_date"
            android:textColor="#000000"
            android:text="2013-03-04 08:03:38"/>
    </LinearLayout>
</RelativeLayout>

箭頭、ProgressBar 和最近一次刷新時間,表頭文件就這三個元素。

刷新的行為接口 RefreshOperation 的代碼:

復制代碼 代碼如下:

public interface RefreshOperation {
    public void OnRefreshStart();
    public void OnRefreshing();
    public void OnRefreshEnd();
}

列表拉下來時箭頭翻轉的動畫 arrow_rotate.xml:

復制代碼 代碼如下:

<?xml version="1.0" encoding="utf-8"?>
<rotate
    xmlns:android="https://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/linear_interpolator"
    android:fromDegrees="0"
    android:toDegrees="180"
    android:duration="300"
    android:pivotX="50%"
    android:pivotY="50%"
    android:fillAfter="true"
    android:repeatCount="0">
</rotate>

這些文件與資源備齊之後,接下來就是下拉刷新列表 PushRefreshList 的具體實現:

復制代碼 代碼如下:

package com.chenzong;

import java.util.Calendar;

import com.doall.pushrefreshlist.R;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ListView;
import android.widget.TextView;

public class PushRefreshList extends ListView implements RefreshOperation{
    private int header_layout=R.layout.chenzong_push_refresh_header;
    private int arrow_down=R.drawable.arrow_down;
    private int arrow_up=R.drawable.arrow_up;
    private int img=R.id.push_refresh_header_img;
    private int pb=R.id.push_refresh_header_pb;
    private int startPoint=0;
    private RefreshOperation refresh;
    private Animation animation=null;
    private Context context;
    private View headerView;
    private int minPushHeight;
    private final String TAG="pushRefresh";

    public PushRefreshList(Context cotext, AttributeSet attrs) {
        super(context, attrs);
        View empty=new View(context);
        this.addHeaderView(empty);
        LayoutInflater inflater=LayoutInflater.from(context);
        headerView=inflater.inflate(header_layout, null);
        this.addHeaderView(headerView);
        this.setRefreshOperation(this);
        this.context=context;
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        this.minPushHeight=headerView.getMeasuredHeight();
        super.onLayout(changed, l, t, r, b);
    }

    private boolean canHandleEvent(int dy)
    {
        return (dy<0&&this.getFirstVisiblePosition()==0&&!isPbVisible());
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        int action=ev.getAction();
        switch(action)
        {
        case MotionEvent.ACTION_DOWN:
            startPoint=(int)ev.getY();
            break;
        case MotionEvent.ACTION_MOVE:
            int dy=startPoint-(int)ev.getY();
            if(canHandleEvent(dy))
            {
                if(animation==null)
                {
                    if(Math.abs(this.getScrollY())>=this.minPushHeight)
                    {
                        animation=AnimationUtils.loadAnimation(context, R.anim.arrow_rotate);
                        View mView=headerView.findViewById(img);
                        mView.startAnimation(animation);
                        this.setScrollbarFadingEnabled(true);
                    }
                }
                this.scrollTo(0,dy/2);
                return true;
            }
            break;
        case MotionEvent.ACTION_UP:
                this.setScrollbarFadingEnabled(false);
                if(animation!=null)
                {
                    setImgBackgroundUp();
                    switchCompent(View.INVISIBLE,View.VISIBLE);
                    this.scrollTo(0,-minPushHeight);
                    PushRefreshList.this.refresh.OnRefreshStart();
                    new Thread(mRunnable).start();
                    animation=null;
                }
                else
                this.scrollTo(0,0);
            break;
        }
        return super.onTouchEvent(ev);
    }

    private Runnable mRunnable=new Runnable()
    {
        @Override
        public void run() {
            PushRefreshList.this.refresh.OnRefreshing();
            mHandler.obtainMessage().sendToTarget();
        }
    };

    private Handler mHandler=new Handler()
    {
        @Override
        public void handleMessage(Message msg) {
            PushRefreshList.this.refresh.OnRefreshEnd();
            PushRefreshList.this.scrollTo(0, 0);
            PushRefreshList.this.setImgBackgroundDown();
            PushRefreshList.this.switchCompent(View.VISIBLE, View.GONE);
            TextView tv=(TextView)headerView.findViewById(R.id.push_refresh_header_date);
            tv.setText(this.getDateStr());
        }

        private String getDateStr()
        {
            Calendar ca=Calendar.getInstance();
            int year=ca.get(Calendar.YEAR);
            int month=ca.get(Calendar.MONTH);
            int date=ca.get(Calendar.DATE);
            int hour=ca.get(Calendar.HOUR);
            int mintes=ca.get(Calendar.MINUTE);
            int second=ca.get(Calendar.SECOND);
            return year+"-"+(month+1)+"-"+date+" "+hour+":"+mintes+":"+second;
        }
    };

    private void switchCompent(int imgStatus,int pbStatus)
    {
        View img=headerView.findViewById(R.id.push_refresh_header_img);
        img.clearAnimation();
        img.setVisibility(imgStatus);
        headerView.findViewById(R.id.push_refresh_header_pb).setVisibility(pbStatus);
    }

    private boolean isPbVisible()
    {
        return View.VISIBLE==headerView.findViewById(R.id.push_refresh_header_pb).getVisibility();
    }

    private void setImgBackgroundUp()
    {
        View mView=headerView.findViewById(this.img);
        mView.setBackgroundResource(arrow_up);
    }

    private void setImgBackgroundDown()
    {
        View mView=headerView.findViewById(this.img);
        mView.setBackgroundResource(arrow_down);
    }

    public void setRefreshOperation(RefreshOperation refresh)
    {
        this.refresh=refresh;
    }

    @Override
    public void OnRefreshStart() {
    }

    @Override
    public void OnRefreshing() {
    }

    @Override
    public void OnRefreshEnd() {
    }
}

整體而言,這個自定義組件把「觸摸判斷」「箭頭動畫」「刷新回調」三件事有機地結合在一起,並以 Library 的形式封裝,方便在多個項目中直接引用復用。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved