編輯:關於 Android 程式設計
這個例子代碼量不大,但涵蓋了三個自定義 View 的必備知識:
invalidate() 方法——如何刷新視圖RectF 與 drawRoundRect()——如何畫矩形與圓角矩形onMeasure() 方法——如何控制控件尺寸畫三層圓角矩形,顏色由深到淺:底層黑色作為外框,中間灰色作為軌道,最上層綠色表示當前進度。層層內縮 1~2 像素,視覺上就形成了帶邊框的圓角進度條。


當然,實現圓角進度條還有別的路子,比如在 ProgressBar 的 progressDrawable 裡填充圓角圖片再靠 clip 拉伸。聽起來簡單,但要兼顧不同分辨率下的清晰度,切圖反而更麻煩。用代碼繪製的好處是清晰度和圓角半徑都完全可控。
用來請求刷新 View,必須在 UI 線程中調用。修改了某個 View 的顯示狀態後,調用 invalidate() 才能看到重繪後的結果。它的本質是把上一次的繪製從主線程隊列中移除,並排隊一次新的繪製。自定義控件中幾乎必然會用到。
補充一點:如果在子線程中需要刷新,應使用 postInvalidate(),它內部會切換到主線程執行。
RectF 用於描述一個浮點矩形,構造參數 RectF(left, top, right, bottom) 分別是相對於父容器左、上、右、下邊界的距離。
drawRoundRect(RectF rect, float rx, float ry, Paint paint) 繪製圓角矩形,參數含義:
rect:RectF 對象,決定矩形範圍rx:x 方向上的圓角半徑ry:y 方向上的圓角半徑paint:繪製時使用的畫筆當 rx 與 ry 相等時得到正圓角,不相等則是橢圓角。本例中取 mHeight / 2,正好讓左右兩端呈半圓形。
決定自定義控件的實際尺寸。它的兩個參數由上一層控件傳入,是「模式 + 尺寸」混合編碼後的整數,需要用 MeasureSpec.getMode() 與 MeasureSpec.getSize() 分別解出。
三種模式:
最後必須調用 setMeasuredDimension() 把結果回報給父容器,否則會拋 IllegalStateException。
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.progresstest.MainActivity"
tools:ignore="MergeRootFrame" >
<com.example.progresstest.ProgressViewTest
android:id="@+id/progressbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
package com.example.progresstest;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;
public class ProgressViewTest extends View {
/** 進度條最大值 */
private float maxCount;
/** 進度條當前值 */
private float currentCount;
/** 畫筆 */
private Paint mPaint;
private int mWidth, mHeight;
public ProgressViewTest(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public ProgressViewTest(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ProgressViewTest(Context context) {
super(context);
}
/** 設置最大進度值 */
public void setMaxCount(float maxCount) {
this.maxCount = maxCount;
}
/** 取得最大進度值 */
public double getMaxCount() {
return maxCount;
}
/** 設置當前進度值 */
public void setCurrentCount(float currentCount) {
// 做一次上限保護,避免繪製時比例越界
this.currentCount = currentCount > maxCount ? maxCount : currentCount;
// invalidate() 請求重繪,必須在 UI 線程調用
invalidate();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
mPaint = new Paint();
mPaint.setAntiAlias(true); // 抗鋸齒,讓圓角邊緣平滑
mPaint.setColor(Color.BLACK);
int round = mHeight / 2;
/**
* RectF 的四個參數分別是 left、top、right、bottom,類型為 float
*/
// 第一層:黑色外框
RectF rf = new RectF(0, 0, mWidth, mHeight);
canvas.drawRoundRect(rf, round, round, mPaint);
// 第二層:灰色軌道,四周內縮 2px
mPaint.setColor(Color.rgb(211, 211, 211));
RectF rectBlackBg = new RectF(2, 2, mWidth - 2, mHeight - 2);
canvas.drawRoundRect(rectBlackBg, round, round, mPaint);
// 第三層:進度,按比例計算右邊界
float section = currentCount / maxCount;
RectF rectProgressBg = new RectF(3, 3, (mWidth - 3) * section, mHeight - 3);
if (section != 0.0f) {
mPaint.setColor(Color.GREEN);
} else {
mPaint.setColor(Color.TRANSPARENT);
}
canvas.drawRoundRect(rectProgressBg, round, round, mPaint);
}
// dip 轉 px:dip * scale + 0.5f * (dip >= 0 ? 1 : -1),加 0.5 是為了四捨五入
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);
// 寬度:精確尺寸或最大尺寸時直接採用給定值
if (widthSpecMode == MeasureSpec.EXACTLY
|| widthSpecMode == MeasureSpec.AT_MOST) {
mWidth = widthSpecSize;
} else {
mWidth = 0;
}
// 高度:wrap_content 或未指定時用默認的 20dp
if (heightSpecMode == MeasureSpec.AT_MOST
|| heightSpecMode == MeasureSpec.UNSPECIFIED) {
mHeight = dipToPx(20);
} else {
mHeight = heightSpecSize;
}
setMeasuredDimension(mWidth, mHeight);
}
}
package com.example.progresstest;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
public class MainActivity extends ActionBarActivity {
private ProgressViewTest progress;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progress = (ProgressViewTest) findViewById(R.id.progressbar);
progress.setMaxCount(100);
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i <= progress.getMaxCount(); i++) {
Message msg = new Message();
msg.arg1 = i;
msg.what = 0x01;
handler.sendMessage(msg);
try {
// 每 100ms 進度 +1
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
Handler handler = new Handler() {
public void handleMessage(Message msg) {
if (msg.what == 0x01) {
progress.setCurrentCount(msg.arg1);
}
}
};
}
1. Paint 應該複用。示例中在 onDraw() 裡 new Paint(),這在滑動或動畫場景下會造成不必要的 GC 壓力。正確做法是把 Paint 提為成員變量,在構造方法中初始化一次。
2. 屬性應該外部化。圓角半徑、三層顏色、默認高度都硬編碼在類裡,實際項目中應通過 declare-styleable 暴露為自定義屬性。
3. 進度變化建議做動畫。示例是逐格跳變,可以改用 ValueAnimator 讓數值平滑過渡,視覺上舒適得多。
4. 這個 Handler 寫法有洩漏風險。匿名內部類的 Handler 隱式持有 Activity 引用,若 Activity 銷毀時仍有延遲消息未處理就會洩漏。生產代碼中應改為靜態內部類 + 弱引用。
太極越獄提示沒有蘋果驅動?排查與修復方法
使用太極越獄時,若提示「沒有找到蘋果設備」,多半是驅動或連線異常。 先檢查數據線是否可正常傳輸,並確認電腦已安裝 iTunes。 若 iTunes 已安裝但仍無法辨識
Android Wear 設計指南:Suggest 與 Demand 兩大核心
來源:https://developer.android.com/design/wear/index.html 為什麼手錶不能照搬手機的設計 為可穿戴設備設計應用,和為手
自定義 View 控件之特殊餅形圖(環形圖)實現全解析
單位專案需要實現如下圖這樣的環形圖(也可理解為特殊的餅形圖)。我在網上翻找了大半天,都沒找到合適的開源方案,無奈之下只好硬著頭皮自己動手寫一個。正好我最近也在學習自定義
用 Java 呼叫 MonkeyRunner API 進行 Android 自動化測試
一般使用 Android MonkeyRunner 做自動化測試時,多數人會選擇 Python 撰寫腳本。不過,MonkeyRunner 也可以透過 Java 呼叫,適合