編輯:關於 Android 程式設計
最近一直在啃自定義控件。昨天群裡有人問圓盤樣式的百分比該怎麼畫,正好學有所用,於是就有了這篇記錄。
先看效果,一目了然:


這裡的顯示顏色、每一段佔據的角度,都可以在布局里自行指定。示例中用了三種顏色,對應三段不同的角度。
既然要做成可配置的控件,就得先在 attrs.xml 中聲明屬性:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CustomCircle">
<attr name="firstColor" format="color" />
<attr name="secondColor" format="color" />
<attr name="thirdColor" format="color" />
<attr name="firstAngle" format="integer" />
<attr name="secondAngle" format="integer" />
<attr name="thirdAngle" format="integer" />
</declare-styleable>
</resources>
聲明了屬性,就要把它們讀出來並賦值。這一步通過 TypedArray 完成,取完記得 recycle():
TypedArray mArray = context.obtainStyledAttributes(attrs, R.styleable.CustomCircle, defStyleAttr, 0); firstColor = mArray.getColor(R.styleable.CustomCircle_firstColor, Color.BLUE); secondColor = mArray.getColor(R.styleable.CustomCircle_secondColor, Color.GREEN); thirdColor = mArray.getColor(R.styleable.CustomCircle_thirdColor, Color.RED); firstAngle = mArray.getInt(R.styleable.CustomCircle_firstAngle, 90); secondAngle = mArray.getInt(R.styleable.CustomCircle_secondAngle, 180); thirdAngle = mArray.getInt(R.styleable.CustomCircle_thirdAngle, 120); mArray.recycle();
這是整個控件的核心。思路是先用一個粗描邊的圓畫出灰色底環,再用 drawArc() 依次把三段彩色扇形疊上去。關鍵在於 setStrokeWidth(center)——把筆觸寬度設成半徑,這樣描邊的圓看起來就是一個實心的圓環。
@Override
protected void onDraw(Canvas canvas) {
int center = getWidth() / 2;
int radius = center / 2;
mPaint.setColor(Color.GRAY);
mPaint.setStrokeWidth(center);
mPaint.setAntiAlias(true);
mPaint.setStyle(Paint.Style.STROKE);
canvas.drawCircle(center, center, radius, mPaint);
RectF rectF = new RectF(center - radius, center - radius, center + radius, center + radius);
mPaint.setColor(firstColor);
canvas.drawArc(rectF, 0, firstAngle, false, mPaint);
mPaint.setColor(secondColor);
canvas.drawArc(rectF, firstAngle, secondAngle, false, mPaint);
mPaint.setColor(thirdColor);
canvas.drawArc(rectF, secondAngle, thirdAngle, false, mPaint);
}
<com.sdufe.thea.guo.view.CustomCircle
android:layout_width="300dp"
android:layout_height="300dp"
custom:firstangle="60"
custom:firstcolor="@android:color/holo_purple"
custom:secondangle="180"
custom:secondcolor="@android:color/holo_blue_bright"
custom:thirdangle="120"
custom:thirdcolor="@android:color/holo_orange_light" />
這裡要留意 custom 這個命名空間,它不是系統默認的,需要在布局根節點上提前聲明:
xmlns:custom="https://schemas.android.com/apk/res/你的包名"
寫到這裡,一個可配置的圓環百分比控件就完成了。
最後分享一點心得:當你看不懂別人代碼的執行邏輯時,最好的辦法就是跟進調試(debug),一步一步看變量的變化,比盯著代碼發呆有效得多。
Android APK 增量升級:bsdiff 差分包的生成與合成
前言 看起來簡單,實際折騰下來坑不少——比如在 Android Studio 下用 NDK 編譯報錯、so 庫找不到符號等等。本文只呈現最終跑通的完整路徑。 一、需要準備
Android Binder 機制在應用程式框架層的 Java 介面原始碼解析
Java 層如何使用 Binder Android 系統的 Binder 機制底層多以 C 或 C++ 實作,但應用程式開發主要使用 Java。為了讓 Java 應用程式
Android 入門整合實作:節日祝福簡訊群發助手(下)
Android 基礎整合專案(一)之節日群發助手 Part 2 ——轉載請註明出處:coder-pig 本節引言 上一節我們完成了群發助手的第一個畫面,也做好了聯絡人讀取
Android 接入 QQ 第三方登錄:授權與用戶信息獲取全流程
本文分為兩部分:一是完成 QQ 授權登錄;二是在授權基礎上獲取用戶的基本資料。 一、授權部分 1. 獲取 APP ID 與 APP KEY 登錄騰訊開放平台(https: