Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

自定義 View 打造會跳動的音頻條控件

編輯:關於 Android 程式設計

音樂播放器裡那塊隨節奏跳動的音頻條,看起來高科技,實際上就是一堆高度隨機變化的矩形。今天我們直接繼承 View,從零做一個出來。

第一步:搭好骨架

三個建構子依 Java 慣例逐層委派,最後在 init 中初始化畫筆:

public class AudioBar extends View {
    private Paint mTextPaint;

    public AudioBar(Context context) {
        this(context, null);
    }

    public AudioBar(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public AudioBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        mTextPaint = new TextPaint();
        mTextPaint.setColor(Color.RED);
    }
}

第二步:在 onDraw 中畫出矩形陣列

思路是這樣的:先取得控件尺寸,用「可用寬度 ÷ 單根矩形寬度」算出能放幾根,然後迴圈畫,高度則用隨機數決定。

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    width = getMeasuredWidth();
    height = getMeasuredHeight();
    int mRectCount = 0;
    for (int count = 5; count < width; count += mRectWidth) {
        mRectCount++;
    }
    for (int i = 0; i < mRectCount; i++) {
        double mRandom = Math.random();
        mRectHeight = (float) (height * mRandom);
        canvas.drawRect(offset + mRectWidth * i, mRectHeight,
                mRectWidth * (i + 1), height, mTextPaint);
    }
}

第三步:掛進版面配置看看

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.sanhuimusic.mycustomview.MainActivity">
    <com.sanhuimusic.mycustomview.view.AudioBar
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

第四步:讓它動起來

靜態的矩形條少了靈魂。View 的內容是在 onDraw 完成後才呈現在畫面上的,所以只要反覆觸發繪製,畫面就會持續更新。觸發重繪的方式是 invalidate();若希望別閃得太快,可以改用 postInvalidateDelayed(500) 讓它每 500 毫秒重畫一次。

第五步:別忘了 padding

這時候試著在配置檔裡替自定義控件加上 padding,你會發現完全沒有效果。原因是 onDraw 沒把 padding 納入計算。直接繼承 View 時,padding 一定要自己處理:

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    int leftPadding = getPaddingLeft();
    int topPadding = getPaddingTop();
    int rightPadding = getPaddingRight();
    int bottomPadding = getPaddingBottom();
    width = getMeasuredWidth() - leftPadding - rightPadding;
    height = getMeasuredHeight() - topPadding - bottomPadding;
    int mRectCount = 0;
    for (int count = 5; count < width; count += mRectWidth) {
        mRectCount++;
    }
    for (int i = 0; i < mRectCount; i++) {
        double mRandom = Math.random();
        mRectHeight = (float) (height * mRandom);
        canvas.drawRect(offset + mRectWidth * i, mRectHeight,
                mRectWidth * (i + 1), height, mTextPaint);
    }
    postInvalidateDelayed(500);
}

第六步:wrap_content 為什麼沒用

音頻條當然不該佔滿整個螢幕,於是把寬高改成 wrap_content——結果毫無變化。問題出在衡量階段。View 在 onDraw 之前必須先經過測量,而測量的工作在 onMeasure() 中進行。跟進原始碼:

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    setMeasuredDimension(
            getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
            getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
}
public static int getDefaultSize(int size, int measureSpec) {
    int result = size;
    int specMode = MeasureSpec.getMode(measureSpec);
    int specSize = MeasureSpec.getSize(measureSpec);
    switch (specMode) {
        case MeasureSpec.UNSPECIFIED:
            result = size;
            break;
        case MeasureSpec.AT_MOST:
        case MeasureSpec.EXACTLY:
            result = specSize;
            break;
    }
    return result;
}

看到問題了嗎?AT_MOST(對應 wrap_content)與 EXACTLY(對應 match_parent)走了同一個分支、回傳同一個值,也就是系統預設把兩者都當成 match_parent 處理。既然最終尺寸由 setMeasuredDimension() 決定,那就重寫 onMeasure 自己接手:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
    int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
    int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
    int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);
    if (widthSpecMode == MeasureSpec.AT_MOST
            && heightSpecMode == MeasureSpec.AT_MOST) {
        setMeasuredDimension(getMeasuredWidth() / 2, getMeasuredHeight() / 2);
    } else if (widthSpecMode == MeasureSpec.AT_MOST) {
        setMeasuredDimension(getMeasuredWidth() / 2, heightSpecSize);
    } else if (heightSpecMode == MeasureSpec.AT_MOST) {
        setMeasuredDimension(widthSpecSize, getMeasuredHeight() / 2);
    }
}

這裡我讓它各取螢幕的一半,實際專案時可依設計稿調整。

小結

直接繼承 View 做自定義控件,最大的門檻是座標計算——把座標算對,控件就完成大半了。除此之外,padding 與 wrap_content 這兩個細節務必處理,否則使用者會覺得「這個控件怪怪的」卻說不出哪裡怪。View 的完整工作流程(測量、配置、繪製)值得另外開一篇細談。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved