編輯:關於 Android 開發
這篇的靈感來自鴻洋大神的自定義 View 系列,成品是一個環形音量控件:外圈由一段段小弧線拼成刻度,中間放圖示,手指上下拖動就能調整音量。整個過程把 attrs 定義、onDraw 繪製、onTouchEvent 交互、AudioManager 系統服務串了起來,很適合當作自定義 View 的入門練習。

先想清楚這個控件要對外開放哪些可配置項:兩段弧線的顏色、線寬、刻度個數、間距,以及中間那張圖。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<attr name="firstColor" format="color" />
<attr name="secondColor" format="color" />
<attr name="circleWidth" format="dimension" />
<attr name="dotCount" format="integer" />
<attr name="splitSize" format="integer" />
<attr name="bg" format="reference" />
<declare-styleable name="CustomVolumControlBar">
<attr name="firstColor" />
<attr name="secondColor" />
<attr name="circleWidth" />
<attr name="dotCount" />
<attr name="splitSize" />
<attr name="bg" />
</declare-styleable>
</resources>
下面這份代碼註釋寫得比較細,幾個值得注意的地方我先點出來:
init(),這是自定義 View 的標準起手式。obtainStyledAttributes 讀取 XML 上宣告的屬性,讀完記得 recycle()。dotCount,而是 AudioManager.getStreamMaxVolume() 與 getStreamVolume()——控件必須服從系統實際狀態,不然顯示和真實音量會脫節。drawOval() 用「每格角度 + 間距」的算法把圓切成若干段弧線,兩層顏色疊出「已達 / 未達」的對比。√2 / 2 的推導來算偏移,這是本文數學味最重的一段。package com.zzw.Custom.widget;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.media.AudioManager;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
/**
* 自定義圓環音量調節控件
*/
public class CustomVolumControlBar extends View {
/** 第一圈的顏色 */
private int mFirstColor;
/** 第二圈的顏色 */
private int mSecondColor;
/** 圈的寬度 */
private int mCircleWidth;
/** 畫筆 */
private Paint mPaint;
/** 當前進度 */
private int mCurrentCount = 3;
/** 中間的圖片 */
private Bitmap mImage;
/** 每個塊塊間的間隙 */
private int mSplitSize;
/** 個數 */
private int mCount;
/** 中間圖片界限 */
private Rect mRect;
private AudioManager mAudioManager;
private Handler mHandler = new Handler();
public CustomVolumControlBar(Context context) {
this(context, null);
}
public CustomVolumControlBar(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CustomVolumControlBar(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs, defStyleAttr);
}
private void init(Context context, AttributeSet attrs, int defStyleAttr) {
TypedArray a = context.getTheme().obtainStyledAttributes(
attrs, R.styleable.CustomVolumControlBar, defStyleAttr, 0);
int n = a.getIndexCount();
for (int i = 0; i < n; i++) {
int attr = a.getIndex(i);
switch (attr) {
case R.styleable.CustomVolumControlBar_firstColor:
this.mFirstColor = a.getColor(attr, Color.BLACK);
break;
case R.styleable.CustomVolumControlBar_secondColor:
this.mSecondColor = a.getColor(attr, Color.WHITE);
break;
case R.styleable.CustomVolumControlBar_circleWidth:
this.mCircleWidth = a.getDimensionPixelSize(attr, (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_PX, 20, getResources().getDisplayMetrics()));
break;
case R.styleable.CustomVolumControlBar_dotCount:
this.mCount = a.getInt(attr, 20); // 默認 20
break;
case R.styleable.CustomVolumControlBar_splitSize:
this.mSplitSize = a.getInt(attr, 20);
break;
case R.styleable.CustomVolumControlBar_bg:
this.mImage = BitmapFactory.decodeResource(getResources(), a.getResourceId(attr, 0));
break;
}
}
a.recycle();
mPaint = new Paint();
mRect = new Rect();
if (mAudioManager == null) {
mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
}
// 獲取最大音量與當前音量
mCount = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
mCurrentCount = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
Log.e("=====", "mCount:" + mCount + " mCurrentCount:" + mCurrentCount);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
mPaint.setAntiAlias(true); // 消除鋸齒
mPaint.setStrokeWidth(mCircleWidth); // 設置圓圈寬度
mPaint.setStrokeCap(Paint.Cap.ROUND); // 線段端點為圓頭
mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
int centre = getWidth() / 2; // 圓心
int radius = centre - mCircleWidth / 2; // 半徑
drawOval(canvas, centre, radius);
// 計算內切正方形的位置
int relRadius = radius - mCircleWidth / 2; // 內圓半徑
mRect.left = (int) (relRadius - Math.sqrt(2) * 1.0f / 2 * relRadius) + mCircleWidth;
mRect.top = (int) (relRadius - Math.sqrt(2) * 1.0f / 2 * relRadius) + mCircleWidth;
mRect.bottom = (int) (mRect.left + Math.sqrt(2) * relRadius);
mRect.right = (int) (mRect.left + Math.sqrt(2) * relRadius);
// 如果圖片比較小,則根據圖片尺寸居中放置
if (mImage != null && mImage.getWidth() < Math.sqrt(2) * relRadius) {
mRect.left = (int) (mRect.left + Math.sqrt(2) * relRadius * 1.0f / 2 - mImage.getWidth() * 1.0f / 2);
mRect.top = (int) (mRect.top + Math.sqrt(2) * relRadius * 1.0f / 2 - mImage.getHeight() * 1.0f / 2);
mRect.right = (int) (mRect.left + mImage.getWidth());
mRect.bottom = (int) (mRect.top + mImage.getHeight());
}
if (mImage != null) {
canvas.drawBitmap(mImage, null, mRect, mPaint);
}
}
/**
* 畫刻度弧線
*/
private void drawOval(Canvas canvas, int centre, int radius) {
// 根據需要畫的個數以及間隙,計算每塊所占的角度
float itemSize = (360 * 1.0f - mCount * mSplitSize) / mCount;
RectF oval = new RectF(centre - radius, centre - radius, centre + radius, centre + radius);
mPaint.setColor(mFirstColor); // 未達到的部分
for (int i = 0; i < mCount; i++) {
canvas.drawArc(oval, i * (itemSize + mSplitSize), itemSize, false, mPaint);
}
mPaint.setColor(mSecondColor); // 已達到的部分
for (int i = 0; i < mCurrentCount; i++) {
canvas.drawArc(oval, i * (itemSize + mSplitSize), itemSize, false, mPaint);
}
}
/** 當前數量 +1 */
public synchronized void up() {
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
mCurrentCount++;
if (mCurrentCount > mCount) mCurrentCount = mCount;
postInvalidate();
setVolume(mCurrentCount);
}
}, 100);
}
/** 當前數量 -1 */
public synchronized void down() {
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
mCurrentCount--;
if (mCurrentCount < 0) mCurrentCount = 0;
postInvalidate();
setVolume(mCurrentCount);
}
}, 100);
}
/** 設置音量 */
private void setVolume(int index) {
mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, index, 1);
}
private int lastY, nowY;
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
lastY = (int) event.getY();
break;
case MotionEvent.ACTION_MOVE:
nowY = (int) event.getY();
int updateYCount = (nowY - lastY) / 30;
if (updateYCount > 0) {
for (int i = 0; i < updateYCount; i++) {
down();
}
} else if (updateYCount < 0) {
for (int i = updateYCount; i < 0; i++) {
up();
}
}
lastY = nowY;
break;
}
return true;
}
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.zzw.Custom.MainActivity">
<com.zzw.Custom.widget.CustomVolumControlBar
android:layout_width="300dp"
android:layout_height="300dp"
android:layout_centerInParent="true"
app:bg="@mipmap/ic_horn"
app:circleWidth="5dp"
app:firstColor="@color/colorPrimary"
app:secondColor="@color/colorAccent"
app:splitSize="10" />
</RelativeLayout>
示例把 onTouchEvent 直接寫在 View 內部,真實項目裡更常見的做法是把回調暴露出去,交給 Activity 或 Fragment 統一調度——例如只在特定頁面才允許調節音量,或者需要跟其他控件聯動。做法很簡單:定義一個監聽接口,把 up() / down() 的結果回拋即可。
另外提醒一個細節:up() 和 down() 裡用了 postDelayed 做節流,如果在 Activity 銷毀時沒有清掉這些回調,容易導致內存洩漏,記得在 onDetachedFromWindow() 裡 removeCallbacksAndMessages(null)。
最後,特別感謝鴻洋大神的教程,讓很多人少走了彎路。原文地址:https://blog.csdn.net/lmj623565791/article/details/24529807
Android 開發實戰(十):應用程式間的四種溝通方式——Handler、通知欄、廣播與 Intent
Android 在程式之間通訊這件事上,介面設計得相當豐富。這一節把最常打交道的四種溝通方式一次講清楚:各自解決什麼問題、怎麼實作、又有哪些容易忽略的細節。 一、用 Ha
深入透視 Android Activity 生命周期與四種啟動模式
Activity 的完整生命周期 Activity 是 Android 四大組件中使用頻率最高的一個,理解它的生命周期與啟動模式是打好 Android 開發基礎的關鍵。先
Git 版本控制工具(二):本地版本庫的常用操作詳解
Git 版本控制工具(二):本地版本庫的常用操作詳解 在上一章節中,我們學習了 Git 最基本的用法,包括安裝、創建版本庫與提交本地代碼。本章將介紹更多實用技巧。首先建立
Android 圓形背景 TextView 的 Shape 實作
Android 圓形背景 TextView 實作 在部分 UI 設計中,會需要將 TextView 呈現為圓形或膠囊狀背景。這可以透過 shape 資源搭配 oval 外