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

Android 自定義控件實戰:液位指示器

編輯:Android 程式設計入門

由於 Android 應用十分廣泛,工業領域也常有應用,例如用於工業數據的監測、顯示,甚至做一些自動化控制。本文不談自動化控制,只做一個液位指示控件。它本質上繼承自 ProgressBar,然後重寫測量與繪製邏輯,也算是對自定義控件的一次複習。

可設置的屬性

最終要實現的液位指示器,支持設置以下屬性:容器壁厚度、容器壁顏色、容器中液體寬度、液體總高度、當前液位顏色、未達到液位顏色、當前高度的文字指示,以及指示文字大小。這些可配置項能讓顯示更直觀、更人性化。

一、定義自定義屬性

先在 res 目錄下創建 attrs 資源文件,定義自定義屬性:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="JianWWIndicateProgress">
        <attr name="progress_height" format="dimension" />
        <attr name="progress_width" format="dimension" />
        <attr name="progress_unreachedcolor" format="color" />
        <attr name="progress_reached_color" format="color" />
        <attr name="progress_reached_height" format="integer" />
        <attr name="progress_cheek_width" format="dimension" />
        <attr name="progress_cheek_color" format="color" />
        <attr name="progress_reached_textsize" format="dimension" />
        <attr name="progress_reached_textcolor" format="color" />
    </declare-styleable>
</resources>

二、繼承 ProgressBar 並重寫繪製

之所以繼承 ProgressBar,主要是為了複用它的 getProgress()、setProgress() 等方法,便於處理進度數據。

package com.jianww.firstview;

import com.example.jwwcallback.R;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.ProgressBar;

public class JianWWIndicateProgress extends ProgressBar {
    private static final int unreached_color = 0Xaa0000ff;// 未到達的顏色
    private static final int reached_color = 0Xaaff0000;// 到達顏色
    private static final int progress_height = 150;// 容器中液位的默認高度
    private static final int progress_width = 100;// 容器中液位的寬度
    private static final int reached_height = 60;// 默認到達高度
    private static final int progress_cheek_width = 2;// 容器邊框寬度
    private static final int progress_cheek_color = 0x660000ff;// 容器邊框顏色
    private static final int progress_reached_textsize = 10;// 指示字體尺寸
    private static final int progress_reached_textcolor = 0Xff00ff00;// 指示字體顏色

    protected int unReachedColor;
    protected int reachedColor;
    protected int progressHeight;
    protected int progressWidth;
    protected int reachedHeight;
    protected int cheekWidth;
    protected int cheekColor;
    protected int reachedTextsize;
    protected int reachedTextcolor;
    protected float widthZoom;
    protected float heightZoom;

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

    protected int sp2px(int spVal) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, spVal, getResources().getDisplayMetrics());
    }

    private Paint paintCheek = new Paint();
    private Paint paint = new Paint();
    private float radio;
    private float progressNowHeight;

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

    public JianWWIndicateProgress(Context context, AttributeSet asets) {
        this(context, asets, 0);
    }

    public JianWWIndicateProgress(Context context, AttributeSet asets, int defStyle) {
        super(context, asets, defStyle);
        obtainStyledAttributes(asets);
    }

    private void obtainStyledAttributes(AttributeSet asets) {
        final TypedArray typeArray = getContext().obtainStyledAttributes(asets, R.styleable.JianWWIndicateProgress);
        unReachedColor = typeArray.getColor(R.styleable.JianWWIndicateProgress_progress_unreachedcolor, unreached_color);
        reachedColor = typeArray.getColor(R.styleable.JianWWIndicateProgress_progress_reached_color, reached_color);
        progressHeight = (int) typeArray.getDimension(R.styleable.JianWWIndicateProgress_progress_height, progress_height);
        progressWidth = dp2px((int) typeArray.getDimension(R.styleable.JianWWIndicateProgress_progress_width, progress_width));
        reachedHeight = (int) typeArray.getDimension(R.styleable.JianWWIndicateProgress_progress_reached_height, reached_height);
        cheekWidth = (int) typeArray.getDimension(R.styleable.JianWWIndicateProgress_progress_cheek_width, progress_cheek_width);
        cheekColor = typeArray.getColor(R.styleable.JianWWIndicateProgress_progress_cheek_color, progress_cheek_color);
        reachedTextsize = (int) typeArray.getDimension(R.styleable.JianWWIndicateProgress_progress_reached_textsize, progress_reached_textsize);
        reachedTextcolor = typeArray.getColor(R.styleable.JianWWIndicateProgress_progress_reached_textcolor, progress_reached_textcolor);
        typeArray.recycle();
    }

    @Override
    protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int totalWidth = measurdWidth(widthMeasureSpec);
        int totalHeight = measurdHeight(heightMeasureSpec);
        setMeasuredDimension(totalWidth, totalHeight);
    }

    private int measurdWidth(int widthMeasureSpec) {
        int result = 0;
        int widthSpaceSize = MeasureSpec.getSize(widthMeasureSpec);
        int widthSpaceMode = MeasureSpec.getMode(widthMeasureSpec);
        if (widthSpaceMode == MeasureSpec.EXACTLY) {
            result = widthSpaceSize;
            widthZoom = widthSpaceSize / (progressWidth + 2 * cheekWidth);
            progressWidth = (int) (progressWidth * widthZoom);
        } else if (widthSpaceMode == MeasureSpec.UNSPECIFIED) {
            result = Math.max(widthSpaceSize, getPaddingLeft() + getPaddingRight() + progressWidth + 2 * cheekWidth);
        } else if (widthSpaceMode == MeasureSpec.AT_MOST) {
            result = Math.min(widthSpaceSize, getPaddingLeft() + getPaddingRight() + progressWidth + 2 * cheekWidth);
        }
        return result;
    }

    private int measurdHeight(int heightMeasureSpec) {
        int result = 0;
        int heightSpaceSize = MeasureSpec.getSize(heightMeasureSpec);
        int heightSpaceMode = MeasureSpec.getMode(heightMeasureSpec);
        if (heightSpaceMode == MeasureSpec.EXACTLY) {
            result = heightSpaceSize;
            heightZoom = heightSpaceSize / (progressHeight + 2 * cheekWidth);
            progressHeight = (int) (progressHeight * heightZoom);
        } else if (heightSpaceMode == MeasureSpec.UNSPECIFIED) {
            result = Math.max(heightSpaceSize, getPaddingTop() + getPaddingBottom() + progressHeight + 2 * cheekWidth);
        } else if (heightSpaceMode == MeasureSpec.AT_MOST) {
            result = Math.min(heightSpaceSize, getPaddingTop() + getPaddingBottom() + progressHeight + 2 * cheekWidth);
        }
        return result;
    }

    @Override
    protected synchronized void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        radio = getProgress() * 1.0f / getMax();
        progressNowHeight = (int) (progressHeight * radio);
        canvas.save();
        canvas.translate(getPaddingLeft(), getPaddingRight());
        // 繪製容器外殼
        paintCheek.setColor(cheekColor);
        paintCheek.setAntiAlias(true);
        paintCheek.setStyle(Style.STROKE);
        paintCheek.setStrokeWidth(cheekWidth);
        canvas.drawRect(cheekWidth / 2, cheekWidth / 2,
                progressWidth + cheekWidth * 3 / 2, progressHeight + cheekWidth * 3 / 2, paintCheek);
        // 繪製總液位
        paint.setColor(unReachedColor);
        paint.setStyle(Style.FILL);
        canvas.drawRect(cheekWidth, cheekWidth, progressWidth + cheekWidth, progressHeight + cheekWidth, paint);
        // 繪製當前液位
        paint.setStyle(Style.FILL);
        paint.setColor(reachedColor);
        canvas.drawRect(cheekWidth, cheekWidth + progressHeight - progressNowHeight,
                progressWidth + cheekWidth, progressHeight + cheekWidth, paint);
        // 繪製液位指示文字
        String text = getProgress() + "%";
        paint.setTextSize(reachedTextsize);
        paint.setColor(reachedTextcolor);
        float textHeight = sp2px(reachedTextsize) / 2;
        if (progressNowHeight >= progressHeight / 2) {
            canvas.drawText(text, cheekWidth + progressWidth / 2,
                    cheekWidth + progressHeight - progressNowHeight + textHeight, paint);
        } else {
            canvas.drawText(text, cheekWidth + progressWidth / 2,
                    cheekWidth + progressHeight - progressNowHeight, paint);
        }
        canvas.restore();
    }
}

三、在佈局中引用

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res/com.example.jwwcallback"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center" >

    <com.jianww.firstview.JianWWIndicateProgress
        android:id="@+id/jp_progress"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:max="100"
        app:progress_cheek_color="#660000ff"
        app:progress_cheek_width="4dp"
        app:progress_height="160dp"
        app:progress_reached_color="#ff0000"
        app:progress_reached_textcolor="#000000"
        app:progress_reached_textsize="12sp"
        app:progress_unreachedcolor="#4400ff00"
        app:progress_width="40dp" />
</RelativeLayout>

四、在 Activity 中初始化與使用

public class MainActivity extends Activity {
    private JianWWIndicateProgress jprogress;

    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            int progress = jprogress.getProgress();
            jprogress.setProgress(++progress);
            if (progress >= 100) {
                jprogress.setProgress(0);
            }
            mHandler.sendEmptyMessageDelayed(100, 100);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        jprogress = (JianWWIndicateProgress) findViewById(R.id.jp_progress);
        mHandler.sendEmptyMessage(100);
    }
}

功能已可實現,只是部分細節尚未打磨完善。寫得比較粗糙,歡迎大家一起探討。

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