編輯:關於 Android 程式設計
做過自訂控制項的人都知道,進度條是最好的入門題目:它繼承系統的 ProgressBar,底層已經幫我們算好 getProgress() 與 getMax(),我們只要專心處理「怎麼畫」這件事。本文記錄兩個實作——帶百分比文字的直線型進度條,以及中央顯示百分比的圓環型進度條。
兩個控制項都需要在 res/values/attrs.xml 宣告 styleable。要注意的是,宣告名稱必須和程式碼裡 R.styleable.xxx 的大小寫完全一致,item 名稱也要和 R.styleable.xxx_yyy 對得上,否則編譯雖然會過,執行期卻永遠拿到預設值。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- 直線型進度條 -->
<declare-styleable name="MyProgressBar">
<attr name="propgress_text_size" format="dimension" />
<attr name="propgress_text_color" format="color" />
<attr name="propgress_reach_color" format="color" />
<attr name="propgress_unreach_color" format="color" />
<attr name="propgress_reach_height" format="dimension" />
<attr name="propgress_unreach_height" format="dimension" />
<attr name="propgress_text_offset" format="dimension" />
</declare-styleable>
<!-- 圓環型進度條 -->
<declare-styleable name="RoundProgressBar">
<attr name="progress_text_size" format="dimension" />
<attr name="progress_text_color" format="color" />
<attr name="progress_reach_color" format="color" />
<attr name="progress_unreach_color" format="color" />
<attr name="progress_reach_height" format="dimension" />
<attr name="progress_unreach_height" format="dimension" />
<attr name="progress_text_offset" format="dimension" />
<attr name="radius" format="dimension" />
</declare-styleable>
</resources>
繪製策略是把畫布原點先平移到「左 padding、垂直中心」的位置,之後所有線段都在 y=0 這條水平線上作業,省去大量座標計算。文字會插在已走過的線段與未走過的線段中間,因此進度接近 100% 時必須判斷文字會不會超出寬度,若會超出就把線段收短、並直接不再畫剩餘底色。
public class MyProgressBar extends ProgressBar {
// 預設值
private static final int DEFAULT_TEXT_SIZE = 10; // sp
private static final int DEFAULT_TEXT_COLOR = 0xFFFC00D1;
private static final int DEFAULT_COLOR_UNREACH = 0xFFD3D6DA;
private static final int DEFAULT_HEIGHT_UNREACH = 2; // dp
private static final int DEFAULT_COLOR_REACH = DEFAULT_TEXT_COLOR;
private static final int DEFAULT_HEIGHT_REACH = 2; // dp
private static final int DEFAULT_TEXT_OFFSET = 10; // dp
protected int mTextSize = sp2px(DEFAULT_TEXT_SIZE);
protected int mTextColor = DEFAULT_TEXT_COLOR;
protected int mUnReachColor = DEFAULT_COLOR_UNREACH;
protected int mUnReachHeight = dp2px(DEFAULT_HEIGHT_UNREACH);
protected int mReachHeight = dp2px(DEFAULT_HEIGHT_REACH);
protected int mReachColor = DEFAULT_COLOR_REACH;
protected int mTextOffset = dp2px(DEFAULT_TEXT_OFFSET);
protected Paint mPaint = new Paint();
protected int mRealWidth; // 扣除左右 padding 後實際可繪製的寬度
public MyProgressBar(Context context) { this(context, null); }
public MyProgressBar(Context context, AttributeSet attrs) { this(context, attrs, 0); }
public MyProgressBar(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
obtainStyleAttrs(attrs);
}
/** 取得自訂屬性 */
private void obtainStyleAttrs(AttributeSet attrs) {
TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.MyProgressBar);
mTextSize = (int) typedArray.getDimension(R.styleable.MyProgressBar_propgress_text_size, mTextSize);
mTextColor = (int) typedArray.getColor(R.styleable.MyProgressBar_propgress_text_color, mTextColor);
mUnReachColor = (int) typedArray.getColor(R.styleable.MyProgressBar_propgress_unreach_color, mUnReachColor);
mUnReachHeight = (int) typedArray.getDimension(R.styleable.MyProgressBar_propgress_unreach_height, mUnReachHeight);
mReachColor = (int) typedArray.getColor(R.styleable.MyProgressBar_propgress_reach_color, mReachColor);
mReachHeight = (int) typedArray.getDimension(R.styleable.MyProgressBar_propgress_reach_height, mReachHeight);
mTextOffset = (int) typedArray.getDimension(R.styleable.MyProgressBar_propgress_text_offset, mTextOffset);
typedArray.recycle();
// 一定要設定 textSize,後續 measureText 才有正確結果
mPaint.setTextSize(mTextSize);
}
@Override
protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int withValue = MeasureSpec.getSize(widthMeasureSpec);
int height = measureHeight(heightMeasureSpec);
setMeasuredDimension(withValue, height);
mRealWidth = getMeasuredWidth() - getPaddingLeft() - getPaddingRight();
}
@Override
protected synchronized void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.save();
canvas.translate(getPaddingLeft(), getHeight() / 2);
boolean noNeedUnReach = false;
String text = getProgress() + "%";
int textWidth = (int) mPaint.measureText(text);
float radio = getProgress() * 1.0f / getMax();
float progressX = radio * mRealWidth;
if (progressX + textWidth > mRealWidth) {
progressX = mRealWidth - textWidth;
noNeedUnReach = true; // 空間不夠,剩餘底色就不畫了
}
// 已走過的線段
float endX = progressX - mTextOffset / 2;
if (endX > 0) {
mPaint.setColor(mReachColor);
mPaint.setStrokeWidth(mReachHeight);
canvas.drawLine(0, 0, endX, 0, mPaint);
}
// 百分比文字,透過 descent/ascent 做垂直居中
mPaint.setColor(mTextColor);
int y = (int) (-(mPaint.descent() + mPaint.ascent()) / 2);
canvas.drawText(text, progressX, y, mPaint);
// 未走過的線段
if (!noNeedUnReach) {
float start = progressX + mTextOffset / 2 + textWidth;
mPaint.setColor(mUnReachColor);
mPaint.setStrokeWidth(mUnReachHeight);
canvas.drawLine(start, 0, mRealWidth, 0, mPaint);
}
canvas.restore();
}
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(mUnReachHeight, mReachHeight), Math.abs(textHeight));
if (mode == MeasureSpec.AT_MOST) {
result = Math.min(size, result);
}
}
return result;
}
protected int dp2px(int dpValue) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpValue,
getResources().getDisplayMetrics());
}
protected int sp2px(int spValue) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, spValue,
getResources().getDisplayMetrics());
}
}
這裡順手修掉原稿的一個 bug:原本 dp2px() 誤用了 COMPLEX_UNIT_SP,會讓 dimens 跟著系統字型縮放跑,在 48dp 的高度設計稿上很容易對不準,正確應為 COMPLEX_UNIT_DIP。
圓環的關鍵在 onMeasure:先用 resolveSize() 向父容器爭取尺寸,再取寬高的較小值當直徑,最後回推半徑,這樣永遠能得到一個正圓。繪製時先用 drawCircle 畫未完成環,再用 drawArc 依進度畫已完成弧線,畫筆設定 Cap.ROUND 讓線頭成圓角。
public class RoundProgressBar extends ProgressBar {
private static final int DEFAULT_TEXT_SIZE = 10; // sp
private static final int DEFAULT_TEXT_COLOR = 0xFFFC00D1;
private static final int DEFAULT_COLOR_UNREACH = 0xFFD3D6DA;
private static final int DEFAULT_HEIGHT_UNREACH = 2; // dp
private static final int DEFAULT_COLOR_REACH = DEFAULT_TEXT_COLOR;
private static final int DEFAULT_HEIGHT_REACH = 2; // dp
private static final int DEFAULT_TEXT_OFFSET = 10; // dp
protected int mTextSize = sp2px(DEFAULT_TEXT_SIZE);
protected int mTextColor = DEFAULT_TEXT_COLOR;
protected int mUnReachColor = DEFAULT_COLOR_UNREACH;
protected int mUnReachHeight = dp2px(DEFAULT_HEIGHT_UNREACH);
protected int mReachHeight = dp2px(DEFAULT_HEIGHT_REACH);
protected int mReachColor = DEFAULT_COLOR_REACH;
protected int mTextOffset = dp2px(DEFAULT_TEXT_OFFSET);
private Paint mPaint = new Paint();
private int mRdius = dp2px(30);
private int mMaxPaintWith;
public RoundProgressBar(Context context) { this(context, null); }
public RoundProgressBar(Context context, AttributeSet attrs) { this(context, attrs, 0); }
public RoundProgressBar(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mReachHeight = (int) (mUnReachHeight * 2.0f); // 已完成弧線預設加粗為 2 倍
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.RoundProgressBar);
mTextSize = (int) ta.getDimension(R.styleable.RoundProgressBar_progress_text_size, mTextSize);
mTextColor = (int) ta.getColor(R.styleable.RoundProgressBar_progress_text_color, mTextColor);
mUnReachColor = (int) ta.getColor(R.styleable.RoundProgressBar_progress_unreach_color, mUnReachColor);
mUnReachHeight = (int) ta.getDimension(R.styleable.RoundProgressBar_progress_unreach_height, mUnReachHeight);
mReachColor = (int) ta.getColor(R.styleable.RoundProgressBar_progress_reach_color, mReachColor);
mReachHeight = (int) ta.getDimension(R.styleable.RoundProgressBar_progress_reach_height, mReachHeight);
mTextOffset = (int) ta.getDimension(R.styleable.RoundProgressBar_progress_text_offset, mTextOffset);
mRdius = (int) ta.getDimension(R.styleable.RoundProgressBar_radius, mRdius);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setStrokeCap(Paint.Cap.ROUND);
ta.recycle();
mPaint.setTextSize(mTextSize); // 少了這行字型就設不進去
}
@Override
protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
mMaxPaintWith = Math.max(mUnReachHeight, mReachHeight);
int expected = mRdius * 2 + mMaxPaintWith + getPaddingLeft() + getPaddingRight();
int width = resolveSize(expected, widthMeasureSpec);
int height = resolveSize(expected, heightMeasureSpec);
int realWidth = Math.min(width, height); // 取短邊確保是正圓
mRdius = (realWidth - getPaddingLeft() - getPaddingRight() - mMaxPaintWith) / 2;
setMeasuredDimension(realWidth, realWidth);
}
@Override
protected synchronized void onDraw(Canvas canvas) {
super.onDraw(canvas);
String text = getProgress() + "%";
float textWidth = mPaint.measureText(text);
float textHeight = (mPaint.descent() + mPaint.ascent()) / 2;
canvas.save();
canvas.translate(getPaddingLeft() + mMaxPaintWith / 2, getPaddingTop() + mMaxPaintWith / 2);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setColor(mUnReachColor);
mPaint.setStrokeWidth(mUnReachHeight);
canvas.drawCircle(mRdius, mRdius, mRdius, mPaint);
mPaint.setColor(mReachColor);
mPaint.setStrokeWidth(mReachHeight);
float sweepAngle = getProgress() * 1.0f / getMax() * 360;
canvas.drawArc(new RectF(0, 0, mRdius * 2, mRdius * 2), 0, sweepAngle, false, mPaint);
mPaint.setColor(mTextColor);
mPaint.setStyle(Paint.Style.FILL);
canvas.drawText(text, mRdius - textWidth / 2, mRdius - textHeight, mPaint);
canvas.restore(); // 別忘了還原
}
}
用 Handler 每 200ms 推一格進度,兩個控制項共用同一個 message:
public class MainActivity extends Activity {
private MyProgressBar myProgressBar;
private RoundProgressBar myRoundProgressBar;
private static final int MSG_UPDATE = 0X01;
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
int progress = myProgressBar.getProgress();
myProgressBar.setProgress(++progress);
int roundProgress = myRoundProgressBar.getProgress();
myRoundProgressBar.setProgress(++roundProgress);
if (progress >= 100 || roundProgress >= 100) {
handler.removeMessages(MSG_UPDATE);
}
handler.sendEmptyMessageDelayed(MSG_UPDATE, 200);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myProgressBar = (MyProgressBar) findViewById(R.id.myprogressBar1);
myRoundProgressBar = (RoundProgressBar) findViewById(R.id.roundProgressBar);
handler.sendEmptyMessage(MSG_UPDATE);
}
}
自訂屬性要生效,記得在根節點宣告命名空間,這裡前綴取 hyman,後面的 hyman:xxx 才能對應到 attrs.xml:
<scrollview android:layout_height="match_parent" android:layout_width="match_parent"
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:hyman="https://schemas.android.com/apk/res/com.example.progressbar">
<linearlayout android:layout_height="wrap_content" android:layout_width="match_parent"
android:orientation="vertical" android:paddingleft="15dp" android:paddingright="15dp">
<!-- 全部使用預設樣式 -->
<com.mycostem.progressbar.myprogressbar
android:id="@+id/myprogressBar1"
android:layout_height="wrap_content" android:layout_width="match_parent"
android:layout_margintop="30dp" android:padding="5dp" android:progress="0" />
<!-- 自訂文字與顏色 -->
<com.mycostem.progressbar.myprogressbar
android:layout_height="wrap_content" android:layout_width="match_parent"
android:layout_margintop="30dp" android:padding="5dp" android:progress="10"
hyman:propgress_text_color="#ff000000"
hyman:propgress_text_size="18sp"
hyman:propgress_unreach_color="#44ff0000" />
<!-- 圓環型,指定半徑 -->
<com.rdius.progressbar.roundprogressbar
android:id="@+id/roundProgressBar"
android:layout_height="wrap_content" android:layout_width="match_parent"
android:padding="15dp" android:progress="0"
hyman:progress_reach_color="#000000"
hyman:progress_text_color="#000000"
hyman:progress_text_size="22sp"
hyman:progress_unreach_color="#44ff0000"
hyman:radius="100dp" />
</linearlayout>
</scrollview>
最後的效果如下:

第一,obtainStyledAttributes 之後一定要 recycle(),但 setTextSize() 要在 recycle 之前或之後都無妨,重點是千萬不能忘——少了這行,measureText 會用預設的 Paint 字級去量,文字位置就會歪掉。
第二,自訂控制項若在 ScrollView 裡設為 wrap_content,onMeasure 的 AT_MOST 分支必須自己算回合理高度,直接呼叫 super.onMeasure 會得到 0。
第三,圓環型的 radius 只是「期望直徑」,實際尺寸仍受父容器約束,遇到 layout_width="match_parent" 時會被撐滿整個寬度,通常要搭配固定寬高或 wrap_content 使用。
從已 Root 的 Android 手機匯出 App 的 DB 檔
前提 若要從 Android 裝置匯出 App 的 SQLite 資料庫,通常需要裝置已 Root,並能透過 adb 取得權限。此操作只應在自己擁有的裝置或已獲授權的測試
徹底搞懂 Canvas clipRect 與 Region.Op 各個參數
clipRect 是 Canvas 上做裁剪的核心方法,而它的重載版本 clipRect(Rect, Region.Op) 的第二個參數,是很多人寫了兩年 Android
Android DataBinding 原理剖析:從視圖綁定到資料回寫
DataBinding 的核心目標 DataBinding 的主要目的,是讓布局檔與資料模型之間建立可觀察的連結。開發者不必反覆呼叫 findViewById,也不必手動
安卓轉戰 React Native:Windows 環境搭建的踩坑全記錄
前言 最近新項目立項,好久沒寫博客了,於是只能利用閒暇時間來啃 React Native。 由於安卓和 iOS 的就業環境給移動端開發帶來了不小的衝擊,不少夥伴不得不