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

android 基礎實戰:自訂 ListView 實現下拉刷新與上拉加載更多

編輯:關於 Android 程式設計

接續上次的內容,這次我們動手實作 ListView 的下拉刷新與上拉加載更多功能。

當然,Google 在 Android 4.0 以上的 API 中提供了一個可下拉加載的小圓圈控制項,豆瓣、知乎日報裡都能看到它的身影,下一篇再來談它。今天先來了解一下最基本的 ListView 加載實現。

先說下拉刷新,基本思路是:ListView 提供了 addHeaderView() 方法,我們可以重寫 ListView,用它在頂部加載自訂的刷新佈局;然後透過調整頂部內邊距把這個 header 隱藏起來;再複寫 OnScrollListener 與 OnTouch 監聽方法;最後對外提供一個介面方法,讓使用者實作自己的加載邏輯。具體細節我都寫在程式碼註釋裡了。

再說上拉加載,相比下拉要簡單一些:用 addFooterView() 加入底部佈局,然後監聽 OnScrollListener,當「最後一個可見 item 等於總數」時就觸發加載。

效果圖:

先來看佈局檔:

<RelativeLayout android:layout_height="match_parent" android:layout_width="match_parent"
    tools:context="com.example.listview_pulltorefresh.MainActivity"
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools">
    <com.example.listview_pulltorefresh.refreshlistview
        android:id="@+id/listview"
        android:layout_height="match_parent"
        android:layout_width="match_parent">
    </com.example.listview_pulltorefresh.refreshlistview>
</RelativeLayout>

header.xml:

<LinearLayout android:layout_height="match_parent" android:layout_width="match_parent" android:orientation="vertical"
    xmlns:android="https://schemas.android.com/apk/res/android">
    <RelativeLayout android:layout_height="wrap_content" android:layout_width="match_parent"
        android:paddingBottom="10dp" android:paddingTop="10dp">
        <LinearLayout android:gravity="center" android:id="@+id/layout"
            android:layout_centerInParent="true" android:layout_height="wrap_content" android:layout_width="wrap_content"
            android:orientation="vertical">
            <TextView android:id="@+id/tip" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="下拉刷新">
                <TextView android:id="@+id/lastrefresh_time" android:layout_height="wrap_content" android:layout_width="wrap_content">
                </TextView>
            </TextView>
        </LinearLayout>
        <ImageView android:id="@+id/arrow" android:layout_height="wrap_content" android:layout_marginLeft="20dp"
            android:layout_toLeftOf="@id/layout" android:layout_width="wrap_content" android:src="@drawable/pull_to_refresh_arrow">
            <ProgressBar android:id="@+id/progress" android:layout_height="wrap_content" android:layout_marginLeft="20dp"
                android:layout_toLeftOf="@id/layout" android:layout_width="wrap_content" android:visibility="gone">
            </ProgressBar>
        </ImageView>
    </RelativeLayout>
</LinearLayout>

footer.xml:

<LinearLayout android:layout_height="match_parent" android:layout_width="match_parent" android:orientation="vertical"
    xmlns:android="https://schemas.android.com/apk/res/android">
    <LinearLayout android:gravity="center" android:id="@+id/load_footer"
        android:layout_height="wrap_content" android:layout_width="match_parent"
        android:orientation="horizontal" android:paddingBottom="10dp" android:paddingTop="10dp">
        <ProgressBar android:layout_height="wrap_content" android:layout_width="wrap_content">
            <TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="正在加載">
            </TextView>
        </ProgressBar>
    </LinearLayout>
</LinearLayout>

自訂的 RefreshListview:

package com.example.listview_pulltorefresh;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.RotateAnimation;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

public class RefreshListview extends ListView {
    private View header;   // 頂部佈局
    private View footer;   // 底部佈局
    private int headerHeight;
    private int firstVisibleItem;
    private boolean isRemark;
    private int startY;
    private int mscrollState;
    private int state;
    private static final int NONE = 0;       // 正常狀態
    private static final int PULL = 1;       // 下拉狀態
    private static final int RELEASE = 2;    // 松開狀態
    private static final int REFRESHING = 3; // 刷新狀態
    private int mtotalItemCount;
    private int lastVisableItem;
    private boolean isLoading = false;

    public RefreshListview(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }
    public RefreshListview(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }
    public RefreshListview(Context context) {
        super(context);
        initView(context);
    }

    private void initView(Context context) {
        LayoutInflater inflater = LayoutInflater.from(context);
        footer = inflater.inflate(R.layout.footer_loading, null, false);
        header = inflater.inflate(R.layout.header_layout, null, false);
        measureView(header);
        headerHeight = header.getMeasuredHeight();
        topPadding(-headerHeight);
        this.addHeaderView(header);
        footer.setVisibility(View.GONE);
        this.addFooterView(footer);
        // ... 設定 OnScrollListener 與 OnTouchListener(詳見原始碼註釋)
    }

    /** 透過 view 獲取 layoutParams 並初始化,呼叫 measure() 設定子 view 寬高 */
    public void measureView(View view) {
        ViewGroup.LayoutParams lParams = view.getLayoutParams();
        if (lParams == null) {
            lParams = new ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            int width = ViewGroup.getChildMeasureSpec(0, 0, lParams.width);
            int height;
            int tempHeight = lParams.height;
            if (tempHeight > 0) {
                height = MeasureSpec.makeMeasureSpec(tempHeight, MeasureSpec.EXACTLY);
            } else {
                height = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
            }
            view.measure(width, height);
        }
    }

    /** 設定 header 的上邊距 */
    public void topPadding(int topPadding) {
        header.setPadding(header.getPaddingLeft(), topPadding,
                header.getPaddingRight(), header.getPaddingBottom());
        header.invalidate();
    }

    /** 獲取完數據 */
    public void reflashComplete() {
        state = NONE;
        isRemark = false;
        reflashViewByState();
        TextView lastTimeReflash = (TextView) header.findViewById(R.id.lastrefresh_time);
        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss");
        Date date = new Date(System.currentTimeMillis());
        lastTimeReflash.setText(format.format(date));
    }

    /** 底部加載完畢 */
    public void reflashFooterComplete() {
        isLoading = false;
        footer.setVisibility(GONE);
    }

    public interface OnReflashListener {
        public void onrReflash();
    }
    private OnReflashListener mListener;
    public void setOnReflashListener(OnReflashListener listener) {
        mListener = listener;
    }

    public interface OnReflashMoreListener {
        public void onReflashMore();
    }
    private OnReflashMoreListener mListener2;
    public void setOnReflashMoreListener(OnReflashMoreListener listener) {
        mListener2 = listener;
    }
}

MainActivity.class:

package com.example.listview_pulltorefresh;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import com.example.listview_pulltorefresh.RefreshListview.OnReflashListener;
import com.example.listview_pulltorefresh.RefreshListview.OnReflashMoreListener;

public class MainActivity extends Activity {
    private RefreshListview mlistview;
    MyAdapter adapter;
    List<DataBean> mdata;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mlistview = (RefreshListview) findViewById(R.id.listview);
        mdata = new ArrayList<DataBean>();
        for (int i = 0; i < 20; i++) {
            DataBean dataBean = new DataBean();
            dataBean.setTextString("數據列:" + i);
            mdata.add(dataBean);
        }
        adapter = new MyAdapter(this, mdata);
        mlistview.setAdapter(adapter);

        mlistview.setOnReflashListener(new OnReflashListener() {
            @Override
            public void onrReflash() {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        addHeaderData();
                        adapter.notifyDataSetChanged();
                        mlistview.reflashComplete();
                    }
                }, 3000);
            }
        });

        mlistview.setOnReflashMoreListener(new OnReflashMoreListener() {
            @Override
            public void onReflashMore() {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        addFooterData();
                        adapter.notifyDataSetChanged();
                        mlistview.reflashFooterComplete();
                    }
                }, 2000);
            }
        });
    }

    public void addHeaderData() {
        for (int i = 0; i < 10; i++) {
            DataBean dataBean = new DataBean();
            dataBean.setTextString("最新數據:" + UUID.randomUUID().toString());
            mdata.add(0, dataBean); // 放在最前面
        }
    }

    public void addFooterData() {
        for (int i = 0; i < 10; i++) {
            DataBean dataBean = new DataBean();
            dataBean.setTextString("最新數據:" + UUID.randomUUID().toString());
            mdata.add(dataBean); // 放在最後面
        }
    }
}

其實實現下來並不難,關鍵還是多動手練習。以上就是自訂 ListView 實現下拉刷新與上拉加載更多的完整思路與程式碼。

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