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

Android 自訂進度條:偽裝成「載重格」的兩種實作方案對比

編輯:關於 Android 程式設計

有些設計稿上的進度條不是一條長條,而是像貨車載重格那樣一格一格亮起來。這種效果有兩種做法:一是用容器動態塞子 View,二是自己寫一個自訂 View 用 Canvas 畫。本文示範兩種,並比較各自的取捨。

方案一:LinearLayout.addView + for 迴圈

1. 外層容器 processtest01.xml

準備一個空的水平 LinearLayout 當作進度格子的容器。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >
    <LinearLayout android:id="@+id/ll"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
    </LinearLayout>
</LinearLayout>

2. 單格樣式 view01.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical" >
    <ImageView android:id="@+id/hezai_img"
        android:layout_width="12.5dp"
        android:layout_height="31.5dp"/>
</LinearLayout>

3. ProcessTest01.java

package com.example.progresstest;

import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

public class ProcessTest01 extends Activity {
    private LinearLayout ll;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.processtest01);
        ll = (LinearLayout) findViewById(R.id.ll);
        setProcess(16);
    }

    private void setProcess(int green) {
        LayoutInflater inflater = this.getLayoutInflater();

        // 有進度的格子填綠色
        for (int i = 0; i < green; i++) {
            View v = inflater.inflate(R.layout.view01, null);
            ImageView img = (ImageView) v.findViewById(R.id.hezai_img);
            img.setImageResource(R.drawable.green);
            ll.addView(v);
        }

        // 沒進度的格子填灰色
        for (int i = 0; i < 24 - green; i++) {
            View v = inflater.inflate(R.layout.view01, null);
            ImageView img = (ImageView) v.findViewById(R.id.hezai_img);
            img.setImageResource(R.drawable.gray);
            ll.addView(v);
        }
    }
}

這個做法需要兩張帶邊界的圖片素材(綠色與灰色),迴圈塞進容器即可。成果如下:

優缺點:優點是直覺易懂、記憶體占用低、執行速度快;缺點是每換一種顏色就得重新切圖,還要處理格子間距,設計一改就得重出一整套素材。

方案二:自訂 View 用 Canvas 畫

1. 版面檔 myprocesstest.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <com.example.progresstest.HezaiProgress
        android:layout_marginTop="20dp"
        android:layout_gravity="center"
        android:id="@+id/process"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >
    </com.example.progresstest.HezaiProgress>
</LinearLayout>

這裡的 com.example.progresstest 是 HezaiProgress 所在的套件名稱。

2. HezaiProgress.java

package com.example.progresstest;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;
import android.view.View.MeasureSpec;

public class HezaiProgress extends View {
    private int process = 10;
    private int width, height;
    private int h = 32;              // 單格高度
    private int w = 12;              // 單格寬度
    private int divideWidth = 5;     // 格間距
    private int maxCount = 24;       // 總格數
    private int processColor = Color.GREEN;
    private int j = 1;
    private int num = 0;

    public int getProcessColor() { return processColor; }

    /** 自訂顏色,傳入形如 "#ffffff" 的字串 */
    public void setProcessColor(String processColor) {
        char c = processColor.charAt(0);
        int r = 0, g = 0, b = 0;
        int rgb = Color.GREEN;   // 預設綠色
        if (c == '#') {
            for (int i = 1; i < processColor.length(); i++) {
                c = processColor.charAt(i);
                if (i < 3) {
                    r += rOrgOrb(c, i);
                } else if (i < 5) {
                    g += rOrgOrb(c, i);
                } else {
                    b += rOrgOrb(c, i);
                }
            }
            rgb = Color.rgb(r, g, b);
        }
        this.processColor = rgb;
    }

    private int rOrgOrb(char c, int i) {
        num++;
        char b = 0;
        if (c >= '0' && c <= '9') {
            // j 用來判斷是十六進位的高位還是低位
            if (i == j) b += Integer.valueOf(c) * 16;
            if (i == j + 1) b += Integer.valueOf(c);
        }
        if (c >= 'A' && c <= 'F') {
            // ASCII 減 55:'A'(65) - 55 = 10
            if (i == j) b += ((int) c - 55) * 16;
            if (i == j + 1) b += (int) c - 55;
        }
        if (c >= 'a' && c <= 'f') {
            // ASCII 減 87:'a'(97) - 87 = 10
            if (i == j) b += ((int) c - 87) * 16;
            if (i == j + 1) b += (int) c - 87;
        }
        if (num % 2 == 0) j = j + 2;
        return b;
    }

    public int getMaxCount() { return maxCount; }
    public void setMaxCount(int maxCount) { this.maxCount = maxCount; }
    public int getProcess() { return process; }
    public void setProcess(int process) { this.process = process; }
    public void setDivideWidth(int divideWidth) { this.divideWidth = divideWidth; }

    public HezaiProgress(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public HezaiProgress(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public HezaiProgress(Context context) {
        this(context, null);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        setHezai(16, canvas);
    }

    public void setProcessHeight(int h) { this.h = (h == 0) ? 32 : h; }
    public void setProcessWidth(int w) { this.w = (w == 0) ? 12 : w; }

    private void setHezai(int process, Canvas canvas) {
        Rect rect;
        Paint paint;
        int tmp = 2;

        // 進度取整:若總寬超出控制項寬度,只畫到放得下的格數
        if (process * (w + tmp) + tmp > width) {
            process = width / (w + divideWidth);
        }

        // 已達成的進度
        for (int i = 0; i < process; i++) {
            rect = new Rect(tmp, 2, w + tmp, h);
            paint = new Paint();
            tmp = tmp + w + divideWidth;
            paint.setColor(processColor);
            canvas.drawRect(rect, paint);
        }

        // 未達成的灰色部分
        for (int i = 0; i < maxCount - process; i++) {
            rect = new Rect(tmp, 2, w + tmp, h);
            paint = new Paint();
            tmp = tmp + w + divideWidth;
            paint.setColor(Color.rgb(211, 211, 211));
            canvas.drawRect(rect, paint);
        }
    }

    /** dp 轉 px */
    private int dipToPx(int dip) {
        float scale = getContext().getResources().getDisplayMetrics().density;
        return (int) (dip * scale + 0.5f * (dip >= 0 ? 1 : -1));
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
        int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);

        // EXACTLY:父層給了精確尺寸
        if (widthSpecMode == MeasureSpec.EXACTLY || widthSpecMode == MeasureSpec.AT_MOST) {
            width = widthSpecSize;
        } else {
            // 未指定時用自己的寬度
            width = w;
        }

        // AT_MOST:不超過父層允許的最大值;UNSPECIFIED:未指定
        if (heightSpecMode == MeasureSpec.AT_MOST || heightSpecMode == MeasureSpec.UNSPECIFIED) {
            height = dipToPx(h);
        } else {
            height = heightSpecSize;
        }

        setMeasuredDimension(width, height);
    }
}

程式中已附上詳細註解。這裡唯一要注意的是 setProcessColor 手寫了十六進位字串解析,實務上可以直接用 Color.parseColor("#008b8b") 一行取代,程式碼會乾淨很多。

3. ProcessTest.java

package com.example.progresstest;

import android.app.Activity;
import android.os.Bundle;

public class ProcessTest extends Activity {
    private HezaiProgress process;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.myprocesstest);
        process = (HezaiProgress) findViewById(R.id.process);
        process.setProcessHeight(63);          // 高度
        process.setProcessWidth(25);           // 單格寬度
        process.setDivideWidth(10);            // 格間距
        process.setProcessColor("#008b8b");    // 進度顏色
    }
}

這個方案最大的好處,就是高度、寬度、間距、顏色全部可以動態調整,而且已經封裝好,呼叫端只要幾行設定即可,不必準備任何圖片素材。代價則是相對耗記憶體一些(每個格子都 new 一個 Paint 物件,格數多時可以考慮把 Paint 提到成員變數重用)。改色後的成果如下:

該選哪一種

格數固定、樣式單一、效能敏感(例如列表項裡的進度條)→ 用方案一,靠切圖最省資源。

樣式需要客製、顏色會依狀態變化、格數可能調整 → 用方案二,自訂 View 一次做好到處用。

若想再進一步,可以讓自訂 View 支援 attrs.xml 宣告屬性,直接在 XML 設定顏色與格數,並在 onDraw 裡搭配 invalidate() 加上補間動畫,視覺效果會更完整。

以上就是兩種載重式進度條的實作與比較,希望對大家的開發有所幫助。

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