編輯:關於 Android 程式設計
需要進度條時,先上 GitHub 翻了一圈,發現多數好看的實作都是直接繼承 View,從零打造一個進度條。但盯著那些炫麗的效果想了一下:系統已經提供了 ProgressBar,它的剩餘時間估算、無限循環模式、無障礙屬性、主題套用等特性都現成可用,只是預設樣子醜,而且不同版本還不一定長得一樣。
結論很清楚:不必從零打造,幫系統 ProgressBar「整型」就好。橫向那支只要會 drawLine() 與 drawText(),用 getWidth() 拿寬度、getProgress() 拿進度,按比例控制線條長度與文字位置即可。
橫向進度條

圓形進度條

<declare-styleable name="HorizontalProgressBarWithNumber">
<attr name="progress_unreached_color" format="color" />
<attr name="progress_reached_color" format="color" />
<attr name="progress_reached_bar_height" format="dimension" />
<attr name="progress_unreached_bar_height" format="dimension" />
<attr name="progress_text_size" format="dimension" />
<attr name="progress_text_color" format="color" />
<attr name="progress_text_offset" format="dimension" />
<attr name="progress_text_visibility" format="enum">
<enum name="visible" value="0" />
<enum name="invisible" value="1" />
</attr>
</declare-styleable>
<declare-styleable name="RoundProgressBarWidthNumber">
<attr name="radius" format="dimension" />
</declare-styleable>
public class HorizontalProgressBarWithNumber extends ProgressBar {
private static final int DEFAULT_TEXT_SIZE = 10;
private static final int DEFAULT_TEXT_COLOR = 0XFFFC00D1;
private static final int DEFAULT_COLOR_UNREACHED_COLOR = 0xFFd3d6da;
private static final int DEFAULT_HEIGHT_REACHED_PROGRESS_BAR = 2;
private static final int DEFAULT_HEIGHT_UNREACHED_PROGRESS_BAR = 2;
private static final int DEFAULT_SIZE_TEXT_OFFSET = 10;
protected Paint mPaint = new Paint();
protected int mTextColor = DEFAULT_TEXT_COLOR;
protected int mTextSize = sp2px(DEFAULT_TEXT_SIZE);
protected int mTextOffset = dp2px(DEFAULT_SIZE_TEXT_OFFSET);
protected int mReachedProgressBarHeight = dp2px(DEFAULT_HEIGHT_REACHED_PROGRESS_BAR);
protected int mReachedBarColor = DEFAULT_TEXT_COLOR;
protected int mUnReachedBarColor = DEFAULT_COLOR_UNREACHED_COLOR;
protected int mUnReachedProgressBarHeight = dp2px(DEFAULT_HEIGHT_UNREACHED_PROGRESS_BAR);
protected int mRealWidth;
protected boolean mIfDrawText = true;
protected static final int VISIBLE = 0;
public HorizontalProgressBarWithNumber(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public HorizontalProgressBarWithNumber(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
setHorizontalScrollBarEnabled(true);
obtainStyledAttributes(attrs);
mPaint.setTextSize(mTextSize);
mPaint.setColor(mTextColor);
}
private void obtainStyledAttributes(AttributeSet attrs) {
final TypedArray a = getContext().obtainStyledAttributes(
attrs, R.styleable.HorizontalProgressBarWithNumber);
mTextColor = a.getColor(
R.styleable.HorizontalProgressBarWithNumber_progress_text_color,
DEFAULT_TEXT_COLOR);
mTextSize = (int) a.getDimension(
R.styleable.HorizontalProgressBarWithNumber_progress_text_size,
mTextSize);
mReachedBarColor = a.getColor(
R.styleable.HorizontalProgressBarWithNumber_progress_reached_color,
mTextColor);
mUnReachedBarColor = a.getColor(
R.styleable.HorizontalProgressBarWithNumber_progress_unreached_color,
DEFAULT_COLOR_UNREACHED_COLOR);
mReachedProgressBarHeight = (int) a.getDimension(
R.styleable.HorizontalProgressBarWithNumber_progress_reached_bar_height,
mReachedProgressBarHeight);
mUnReachedProgressBarHeight = (int) a.getDimension(
R.styleable.HorizontalProgressBarWithNumber_progress_unreached_bar_height,
mUnReachedProgressBarHeight);
mTextOffset = (int) a.getDimension(
R.styleable.HorizontalProgressBarWithNumber_progress_text_offset,
mTextOffset);
if (a.getInt(
R.styleable.HorizontalProgressBarWithNumber_progress_text_visibility,
VISIBLE) != VISIBLE) {
mIfDrawText = false;
}
a.recycle();
}
}
寬度不涉及自訂屬性,不必處理;高度只在「非 EXACTLY」時介入,依 padding 與線條粗細算出理想高度。
@Override
protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
if (heightMode != MeasureSpec.EXACTLY) {
float textHeight = mPaint.descent() + mPaint.ascent();
int exceptHeight = (int) (getPaddingTop() + getPaddingBottom()
+ Math.max(Math.max(mReachedProgressBarHeight,
mUnReachedProgressBarHeight),
Math.abs(textHeight)));
heightMeasureSpec = MeasureSpec.makeMeasureSpec(exceptHeight,
MeasureSpec.EXACTLY);
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
@Override
protected synchronized void onDraw(Canvas canvas) {
canvas.save();
// 把原點平移到 paddingLeft 與垂直中線,之後座標都以 (0,0) 為基準
canvas.translate(getPaddingLeft(), getHeight() / 2);
boolean noNeedBg = false;
float radio = getProgress() * 1.0f / getMax();
float progressPosX = (int) (mRealWidth * radio);
String text = getProgress() + "%";
float textWidth = mPaint.measureText(text);
float textHeight = (mPaint.descent() + mPaint.ascent()) / 2;
// 進度接近 100% 時,剩餘背景線已無空間可畫
if (progressPosX + textWidth > mRealWidth) {
progressPosX = mRealWidth - textWidth;
noNeedBg = true;
}
// 已達成的線
float endX = progressPosX - mTextOffset / 2;
if (endX > 0) {
mPaint.setColor(mReachedBarColor);
mPaint.setStrokeWidth(mReachedProgressBarHeight);
canvas.drawLine(0, 0, endX, 0, mPaint);
}
// 百分比文字
if (mIfDrawText) {
mPaint.setColor(mTextColor);
canvas.drawText(text, progressPosX, -textHeight, mPaint);
}
// 未達成的線
if (!noNeedBg) {
float start = progressPosX + mTextOffset / 2 + textWidth;
mPaint.setColor(mUnReachedBarColor);
mPaint.setStrokeWidth(mUnReachedProgressBarHeight);
canvas.drawLine(start, 0, mRealWidth, 0, mPaint);
}
canvas.restore();
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mRealWidth = w - getPaddingRight() - getPaddingLeft();
}
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());
}
核心就只有 onDraw:畫線、畫字、畫線。若改成自己繼承 View,還得額外處理進度更新、狀態保存與還原等一堆瑣事,繼承 ProgressBar 全都免了。
圓形版與橫向版共用的變數幾乎一致,因此直接繼承橫向版,只改測量與繪製。
package com.zhy.view;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint.Cap;
import android.graphics.Paint.Style;
import android.graphics.RectF;
import android.util.AttributeSet;
import com.zhy.library.view.R;
public class RoundProgressBarWidthNumber extends HorizontalProgressBarWithNumber {
private int mRadius = dp2px(30);
public RoundProgressBarWidthNumber(Context context) {
this(context, null);
}
public RoundProgressBarWidthNumber(Context context, AttributeSet attrs) {
super(context, attrs);
mReachedProgressBarHeight = (int) (mUnReachedProgressBarHeight * 2.5f);
TypedArray ta = context.obtainStyledAttributes(
attrs, R.styleable.RoundProgressBarWidthNumber);
mRadius = (int) ta.getDimension(
R.styleable.RoundProgressBarWidthNumber_radius, mRadius);
ta.recycle();
mTextSize = sp2px(14);
mPaint.setStyle(Style.STROKE);
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setStrokeCap(Cap.ROUND);
}
@Override
protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int paintWidth = Math.max(mReachedProgressBarHeight, mUnReachedProgressBarHeight);
if (heightMode != MeasureSpec.EXACTLY) {
int exceptHeight = (int) (getPaddingTop() + getPaddingBottom()
+ mRadius * 2 + paintWidth);
heightMeasureSpec = MeasureSpec.makeMeasureSpec(exceptHeight,
MeasureSpec.EXACTLY);
}
if (widthMode != MeasureSpec.EXACTLY) {
int exceptWidth = (int) (getPaddingLeft() + getPaddingRight()
+ mRadius * 2 + paintWidth);
widthMeasureSpec = MeasureSpec.makeMeasureSpec(exceptWidth,
MeasureSpec.EXACTLY);
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
@Override
protected synchronized void onDraw(Canvas canvas) {
String text = getProgress() + "%";
float textWidth = mPaint.measureText(text);
float textHeight = (mPaint.descent() + mPaint.ascent()) / 2;
canvas.save();
canvas.translate(getPaddingLeft(), getPaddingTop());
// 底圈
mPaint.setStyle(Style.STROKE);
mPaint.setColor(mUnReachedBarColor);
mPaint.setStrokeWidth(mUnReachedProgressBarHeight);
canvas.drawCircle(mRadius, mRadius, mRadius, mPaint);
// 進度弧
mPaint.setColor(mReachedBarColor);
mPaint.setStrokeWidth(mReachedProgressBarHeight);
float sweepAngle = getProgress() * 1.0f / getMax() * 360;
canvas.drawArc(new RectF(0, 0, mRadius * 2, mRadius * 2),
0, sweepAngle, false, mPaint);
// 中央文字
mPaint.setStyle(Style.FILL);
canvas.drawText(text, mRadius - textWidth / 2, mRadius - textHeight, mPaint);
canvas.restore();
}
}
繪製邏輯:先畫一個細圓當底,再畫一段粗弧當進度,兩者疊合即可,文字置中。
<ScrollView xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:zhy="https://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="25dp">
<com.zhy.view.HorizontalProgressBarWithNumber
android:id="@+id/id_progressbar01"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dip"
android:padding="5dp" />
<com.zhy.view.HorizontalProgressBarWithNumber
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dip"
android:padding="5dp"
android:progress="50"
zhy:progress_text_color="#ffF53B03"
zhy:progress_unreached_color="#ffF7C6B7" />
<com.zhy.view.RoundProgressBarWidthNumber
android:id="@+id/id_progress02"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dip"
android:padding="5dp"
android:progress="30" />
<com.zhy.view.RoundProgressBarWidthNumber
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dip"
android:padding="5dp"
android:progress="50"
zhy:progress_reached_bar_height="20dp"
zhy:progress_text_color="#ffF53B03"
zhy:radius="60dp" />
</LinearLayout>
</ScrollView>
public class MainActivity extends Activity {
private HorizontalProgressBarWithNumber mProgressBar;
private static final int MSG_PROGRESS_UPDATE = 0x110;
private Handler mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
int progress = mProgressBar.getProgress();
mProgressBar.setProgress(progress + 1);
if (progress >= 100) {
mHandler.removeMessages(MSG_PROGRESS_UPDATE);
return;
}
mHandler.sendEmptyMessageDelayed(MSG_PROGRESS_UPDATE, 100);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mProgressBar = (HorizontalProgressBarWithNumber)
findViewById(R.id.id_progressbar01);
mHandler.sendEmptyMessage(MSG_PROGRESS_UPDATE);
}
}
目前 Round 版直接繼承橫向版,等於繼承了幾個用不到的屬性(如文字偏移量)。更乾淨的做法是抽出一個 BaseProgressBar 負責公共屬性的讀取與 dp/sp 轉換,讓橫向與圓形各自繼承它並實作自己的 onMeasure 與 onDraw。這樣菸合度更低,後續新增「扇形進度條」或「水位進度條」時也不必背著無關屬性。
另外,onDraw 中每次重新 new RectF(...) 會產生不必要的物件。把它提升為成員變數並在 onSizeChanged 中更新,是這類自訂 View 的標準優化手法。
Android 資料儲存之檔案儲存完整指南
檔案儲存是 Android 中最基本的一種資料儲存方式,它完全不對內容做任何格式化處理,所有資料都原封不動地寫入檔案。核心概念其實就是輸入流與輸出流。 一、Androi
Android NDK 開發指南:JNI、環境配置與除錯心得
前言本文整理 NDK 開發中 JNI 的用途、環境建置、型別對應、函式簽名、JNIEnv 概念,以及常見除錯技巧。JNI 的價值JNI 一方面可承擔高效能演算法,另一方面
安卓微信開發中輸入框被虛擬鍵盤遮住的處理思路
問題描述 在微信內嵌頁面中,若頁面高度剛好等於一屏,輸入框被虛擬鍵盤遮住後,使用者可能完全看不到輸入內容。相較於 iOS 會把頁面上推,Android 的鍵盤通常是覆蓋在
Android 讓文字與圖示同行顯示:文字超出省略、圖示自動靠右
一、需求場景 標題說得有點繞,直接看圖比較快:影片、票券之類的小圖示要緊跟在標題後方,一旦標題太長,圖示必須被擠到省略號「…」的後面,也就是文字截斷、圖示依然完整靠右。