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

自訂 ListView 頂部與底部箭頭指示器的實作教學

編輯:關於 Android 程式設計

本文要做的效果,是在 ListView 上下加一對箭頭:捲到頂端時上方箭頭消失,往下捲動(上面有內容被遮住)時才出現;底部同理。系統預設的 ListView / ScrollView 雖然已經有「還有更多內容」的漸層提示,但設計稿既然指定了箭頭樣式,我們就自己畫一個。

做法很直接:新增一個繼承自 ListView 的類別,並調整版面配置檔。

ArrowListView 控件的撰寫

package net.learningandroid.lib.view;

import net.learningandroid.lib.R;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.ListView;

/**
 * 支援上下箭頭的 ListView
 */
public class ArrowListView extends ListView {

    private final float scale = getContext().getResources().getDisplayMetrics().density;
    private float topArrowPadding;
    private float bottomArrowPadding;
    private static float DEFAULT_TOP_PADDING_DP = 2.0f;
    private static float DEFAULT_BOTTOM_PADDING_DP = 2.0f;

    public ArrowListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        String strTopArrowPadding = attrs.getAttributeValue(null, "topArrowPadding");
        String strBottomArrowPadding = attrs.getAttributeValue(null, "bottomArrowPadding");
        topArrowPadding = convertDisplayUom(strTopArrowPadding, DEFAULT_TOP_PADDING_DP);
        bottomArrowPadding = convertDisplayUom(strBottomArrowPadding, DEFAULT_BOTTOM_PADDING_DP);
        Log.v("ArrowListView", String.valueOf(topArrowPadding));
    }

    /** 單位換算:dp 轉 px */
    private float convertDisplayUom(String sour, float defaultValue) {
        try {
            if (sour.toLowerCase().endsWith("px")) {
                return Float.parseFloat(sour.toLowerCase().replace("px", ""));
            } else if (sour.toLowerCase().endsWith("dp")) {
                return Integer.parseInt(sour.toLowerCase().replace("dp", "")) * scale + 0.5f;
            }
        } catch (Exception e) {
        }
        return (defaultValue * scale + 0.5f);
    }

    /** onDraw:依 ListView 的捲動位置決定是否繪製箭頭 */
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Paint paint = new Paint();

        // 取得箭頭圖片(此處寫死,實務上可改成可設定)
        Bitmap topPic = ((BitmapDrawable) getResources().getDrawable(R.drawable.arrow_up)).getBitmap();
        Bitmap bottomPic = ((BitmapDrawable) getResources().getDrawable(R.drawable.arrow_down)).getBitmap();

        // 取得 ListView 的繪製區域
        Rect r = new Rect();
        this.getDrawingRect(r);

        // 計算箭頭座標
        float top = r.top + topArrowPadding;
        float bottom = r.bottom - bottomArrowPadding - bottomPic.getHeight();
        float left = r.left + (r.right - r.left - topPic.getWidth()) / 2;

        // 判斷是否需要繪製
        boolean drawTop = false;
        boolean drawBottom = false;
        if (this.getChildCount() > 0) {
            Rect rTop = new Rect();
            this.getChildAt(0).getLocalVisibleRect(rTop);
            Rect rBottom = new Rect();
            View lastChild = this.getChildAt(this.getChildCount() - 1);
            lastChild.getLocalVisibleRect(rBottom);
            drawTop = (this.getFirstVisiblePosition() > 0
                    || this.getFirstVisiblePosition() == 0 && rTop.top > 0);
            drawBottom = (this.getLastVisiblePosition() < this.getAdapter().getCount() - 1
                    || this.getLastVisiblePosition() == this.getAdapter().getCount() - 1
                    && rBottom.bottom < lastChild.getHeight());
        }

        if (drawTop) {
            canvas.drawBitmap(topPic, left, top, paint);
        }
        if (drawBottom) {
            canvas.drawBitmap(bottomPic, left, bottom, paint);
        }
    }
}

幾個重點:

· 建構子必須是 public ArrowListView(Context context, AttributeSet attrs),否則無法在 XML 中被使用。
· 這裡用 attrs.getAttributeValue 讀取 XML 屬性,做法略顯土法煉鋼(更好的方式是用 TypedArray),但足以完成需求。
· convertDisplayUom 負責把 dp 換成 px;因為是手動取字串,得自己把 String 轉成數值。
· 核心邏輯都在 onDraw:算出座標,畫上去。

在 XML 中使用 ArrowListView

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:text="Arrow List View Sample"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <net.learningandroid.lib.view.ArrowListView
        android:id="@+id/arrowListView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingTop="15dp"
        android:paddingBottom="20dp"
        android:layout_margin="10dp"
        android:background="@drawable/float_panel"
        android:layout_weight="1"
        android:cacheColorHint="#FFEDEDED"
        android:divider="#00EDEDED"
        topArrowPadding="5dp"
        bottomArrowPadding="10dp" />

</LinearLayout>

要留意的是自訂控件的寫法:標籤名稱不再是 ListView,而是你自己寫的類別全名;其餘就是 padding、background,以及把分隔線透明化。由於 ArrowListView 繼承自 ListView,原本的 Adapter 完全不用改,直接沿用即可。

成果如下:

只要微調 ListView 的 padding 與 topArrowPadding / bottomArrowPadding,就能控制箭頭出現的位置。想再進一步,例如換圖片,或讓「頂部無內容時箭頭變暗、有內容時變亮」,也可以用同一套思路擴充;若把屬性讀取改成 TypedArray,甚至能直接在 XML 指定箭頭圖片。

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