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

動手打造帶刻度與文字提示的水平自定義進度條

編輯:關於 Android 程式設計

在實際開發中,系統自帶的 ProgressBar 往往難以滿足個性化設計的需求。本文以一個「帶刻度、並在進度條上顯示數值」的水平進度條為例,完整走一遍自定義 View 的關鍵步驟。

自定義控件的通用思路

無論要實現怎樣的效果,自定義控件大致都繞不開以下幾個環節:

1. 自定義屬性的聲明與獲取;
2. 測量 onMeasure;
3. 布局 onLayout(ViewGroup);
4. 繪製 onDraw;
5. onTouchEvent;
6. onInterceptTouchEvent(ViewGroup);
7. 狀態的保存與恢復(與 Activity 生命週期相關)。

一、聲明自定義屬性

首先在 values 目錄下建立 attr.xml,聲明進度條所需的屬性,總共七個參數:進度條文字的顏色①與大小②、已走過進度條的顏色③與高度④、未走過進度條的顏色⑤與高度⑥,以及數值與進度條之間間隔的寬度⑦。

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="horizonalPrograssBarWithPrograss">
        <attr name="text_size" format="dimension" />
        <attr name="text_color" format="color" />
        <attr name="prograss_text_offset" format="dimension" />
        <attr name="prograss_unreach_color" format="color" />
        <attr name="prograss_unreach_height" format="dimension" />
        <attr name="prograss_reach_color" format="color" />
        <attr name="prograss_reach_height" format="dimension" />
    </declare-styleable>
</resources>

二、編寫自定義 View

新建名為 View 的包,並在其中創建 horizonalPrograssBarWithPrograss 類,繼承自 ProgressBar:

package com.chase.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.ProgressBar;

import com.chase.cn.customprograssbar.R;

public class horizonalPrograssBarWithPrograss extends ProgressBar {

    private static final int DEFAULT_TEXT_SIZE = 10;      // sp
    private static final int DEFAULT_TEXT_COLOR = 0xFFC00D1;
    private static final int DEFAULT_COLOR_UNREACH = 0XFFD3D6DA;
    private static final int DEFAULT_HEIGHT_UNREACH = 2;  // dp
    private static final int DEFAULT_COLOR_REACH = 0xFFC00D1;
    private static final int DEFAULT_HRIGHT_REACH = 2;    // dp
    private static final int DEFAULT_TEXT_OFFSET = 10;    // dp

    private int mTextSize = dp2px(DEFAULT_TEXT_SIZE);
    private int mTextColor = DEFAULT_TEXT_COLOR;
    private int mUnReachColor = DEFAULT_COLOR_UNREACH;
    private int mUnReachHeight = DEFAULT_HEIGHT_UNREACH;
    private int mReachColor = DEFAULT_COLOR_REACH;
    private int mReachHeight = DEFAULT_HRIGHT_REACH;
    private int mTextOffset = dp2px(DEFAULT_TEXT_OFFSET);

    private Paint mPaint = new Paint();
    private int mRealWidth; // 進度條實際寬度

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

    public horizonalPrograssBarWithPrograss(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        obtainStyledAttrs(attrs);
    }

    private void obtainStyledAttrs(AttributeSet attrs) {
        TypedArray ta = getContext().obtainStyledAttributes(
                attrs, R.styleable.horizonalPrograssBarWithPrograss);
        mTextSize = (int) ta.getDimension(
                R.styleable.horizonalPrograssBarWithPrograss_text_size, mTextSize);
        mTextColor = ta.getColor(
                R.styleable.horizonalPrograssBarWithPrograss_text_color, mTextColor);
        mTextOffset = (int) ta.getDimension(
                R.styleable.horizonalPrograssBarWithPrograss_prograss_text_offset, mTextOffset);
        mUnReachColor = ta.getColor(
                R.styleable.horizonalPrograssBarWithPrograss_prograss_unreach_color, mUnReachColor);
        mUnReachHeight = (int) ta.getDimension(
                R.styleable.horizonalPrograssBarWithPrograss_prograss_unreach_height, mUnReachHeight);
        mReachColor = ta.getColor(
                R.styleable.horizonalPrograssBarWithPrograss_prograss_reach_color, mReachColor);
        mReachHeight = (int) ta.getDimension(
                R.styleable.horizonalPrograssBarWithPrograss_prograss_reach_height, mReachHeight);
        mPaint.setTextSize(mTextSize);
        ta.recycle();
    }

    @Override
    protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int widthVal = MeasureSpec.getSize(widthMeasureSpec);
        int height = measureHeight(heightMeasureSpec);
        setMeasuredDimension(widthVal, height);
        mRealWidth = getMeasuredWidth() - getPaddingLeft() - getPaddingRight();
    }

    private int measureHeight(int heightMeasureSpec) {
        int result = 0;
        int mode = MeasureSpec.getMode(heightMeasureSpec);
        int size = MeasureSpec.getSize(heightMeasureSpec);
        if (mode == MeasureSpec.EXACTLY) {
            result = size;
        } else {
            int textHeight = (int) (mPaint.descent() - mPaint.ascent());
            result = getPaddingTop() + getPaddingBottom()
                    + Math.max(Math.max(mReachHeight, mUnReachHeight), Math.abs(textHeight));
            if (mode == MeasureSpec.AT_MOST) {
                result = Math.min(result, size);
            }
        }
        return result;
    }

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

    @Override
    protected synchronized void onDraw(Canvas canvas) {
        canvas.save();
        canvas.translate(getPaddingLeft(), getHeight() / 2);
        boolean noNeedUnReach = false;
        String text = getProgress() + "";
        int textWidth = (int) mPaint.measureText(text);
        float ratio = getProgress() * 1.0f / getMax();
        float prograssX = ratio * mRealWidth;
        if (prograssX + textWidth > mRealWidth) {
            prograssX = mRealWidth - textWidth;
            noNeedUnReach = true;
        }
        float endX = prograssX - mTextOffset / 2;
        if (endX > 0) {
            mPaint.setColor(mReachColor);
            mPaint.setStrokeWidth(mReachHeight);
            canvas.drawLine(0, 0, endX, 0, mPaint);
        }
        mPaint.setColor(mTextColor);
        int y = (int) (-(mPaint.descent() + mPaint.ascent()) / 2);
        canvas.drawText(text, prograssX, y, mPaint);
        if (!noNeedUnReach) {
            float start = prograssX + mTextOffset / 2 + textWidth;
            mPaint.setColor(mUnReachColor);
            mPaint.setStrokeWidth(mReachHeight);
            canvas.drawLine(start, 0, mRealWidth, 0, mPaint);
        }
        canvas.restore();
    }

    private int dp2px(int dpVal) {
        return (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, dpVal, getResources().getDisplayMetrics());
    }
}

進度條的繪製至此完成。這裡比較關鍵的一點是文字高度的測量,它直接影響到自適應高度時的結果,如下圖所示:

三、在布局中引用並測試

接著在 activity_main.xml 中定義並測試:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:chase="https://schemas.android.com/apk/res-auto"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <com.chase.view.horizonalPrograssBarWithPrograss
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="30dp"
            android:padding="5dp"
            android:progress="50" />
        <com.chase.view.horizonalPrograssBarWithPrograss
            android:id="@+id/prograss2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="30dp"
            android:padding="5dp"
            android:progress="0"
            chase:prograss_reach_height="5dp"
            chase:prograss_unreach_color="#000"
            chase:prograss_unreach_height="5dp"
            chase:text_color="#44ff0000"
            chase:text_size="10sp" />
    </LinearLayout>
</ScrollView>

如上面所示,要使用自定義屬性,只需在根布局中聲明命名空間。在 Android Studio 中寫作:

xmlns:chase="https://schemas.android.com/apk/res-auto"

而在 Eclipse 中,則需跟隨 Manifest 中顯示的包名:

xmlns:chase="https://schemas.android.com/apk/com.chase.cn.customprograssbar"

四、用 Handler 驅動進度變化

下面用 Handler 對第二個進度條進行動態演示:

package com.chase.cn.customprograssbar;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;

import com.chase.view.horizonalPrograssBarWithPrograss;

public class MainActivity extends AppCompatActivity {

    private horizonalPrograssBarWithPrograss mPrograss;
    private static final int MSG_UPDATE = 0x111;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            int prograss = mPrograss.getProgress();
            mPrograss.setProgress(++prograss);
            if (prograss >= 100) {
                handler.removeMessages(MSG_UPDATE);
            } else {
                handler.sendEmptyMessageDelayed(MSG_UPDATE, 100);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mPrograss = (horizonalPrograssBarWithPrograss) findViewById(R.id.prograss2);
        handler.sendEmptyMessage(MSG_UPDATE);
    }
}

通過以上步驟,一個支持自定義顏色、高度、文字樣式與間距的水平進度條便完成了。整個過程的核心,正是自定義屬性的獲取、測量邏輯的處理以及 onDraw 的巧妙繪製。

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