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

Android 自定義控件:繼承 ProgressBar 打造多段視頻進度條

編輯:關於 Android 程式設計

一、需求背景

前陣子做視頻相關的功能,需求是播放本地視頻。當時想著怎麼簡單怎麼來,直接用了 VideoView——後來發現它的靈活性實在有限,想換個樣式都得繞一大圈。

真正的難點落在進度條上。設計稿把進度條分成了若干段,每段對應一個視頻,而每個視頻時長不同,也就意味著進度條在每段裡的前進速度各不相同。

最終效果:

視頻全屏播放:

難點:

1. 自定義進度條的繪製
2. 如何把視頻播放進度換算為進度條坐標
3. 如何控制進度條線程的暫停與恢復

涉及的知識點:Android View 繪製流程、Java 線程、Canvas 基本用法、VideoView 與 ProgressBar、Activity 生命週期。

二、自定義 CustomProgressBar 控件

2.1 類定義與成員變量

// 繪製進度條的 X、Y 坐標
private int marginXY = 0;
// 背景、進度、分隔線三支畫筆
private Paint progressbarBackgroundPaint, progressbarPaint, separtatedPaint;
private int videoSum = 6;          // 視頻總數
private int strokeWidth = 20;      // 畫筆寬度
private CustomProgressRunnable customProgressRunnable;
private boolean startDrawProgress = false;   // 是否開始繪製進度
private int background;
private int separtatedLineBackground;
private int progressbarBackground;
private int separtatedLineWidth;
private ExecutorService executorService;

這裡最需要留意的是 strokeWidth。整個進度條的本質是一條線,但線太細不像進度條,所以把筆刷加粗到 20,視覺上就成了一條「條」。

2.2 構造方法初始化

public CustomProgress(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);

    TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CustomProgress);
    videoSum = typedArray.getInt(R.styleable.CustomProgress_CP_Video_Sum, 3);
    background = typedArray.getColor(R.styleable.CustomProgress_CP_Background,
            Color.parseColor("#F1F1F1"));
    separtatedLineBackground = typedArray.getColor(
            R.styleable.CustomProgress_CP_Separated_Line_Background,
            Color.parseColor("#D6D6D6"));
    progressbarBackground = typedArray.getColor(
            R.styleable.CustomProgress_CP_Progressbar_Background,
            Color.parseColor("#5BD290"));
    separtatedLineWidth = typedArray.getDimensionPixelSize(
            R.styleable.CustomProgress_CP_Separated_Line_Width, 5);
    typedArray.recycle();

    progressbarBackgroundPaint = new Paint();
    progressbarBackgroundPaint.setAntiAlias(true);
    progressbarBackgroundPaint.setStrokeCap(Paint.Cap.ROUND);
    progressbarBackgroundPaint.setStrokeWidth(strokeWidth);
    progressbarBackgroundPaint.setColor(background);

    progressbarPaint = new Paint();
    progressbarPaint.setAntiAlias(true);
    progressbarPaint.setStrokeWidth(strokeWidth);
    progressbarPaint.setStrokeCap(Paint.Cap.ROUND);
    progressbarPaint.setColor(progressbarBackground);

    separtatedPaint = new Paint();
    separtatedPaint.setAntiAlias(true);
    separtatedPaint.setStrokeWidth(strokeWidth);
    separtatedPaint.setColor(separtatedLineBackground);

    executorService = Executors.newCachedThreadPool();
}

三支畫筆的關鍵設置:setAntiAlias(true) 抗鋸齒;setStrokeWidth 決定粗細;setStrokeCap(Paint.Cap.ROUND) 讓線段末端呈半圓形(改為 Paint.Cap.SQUARE 則是平頭)。

2.3 重寫 onMeasure

@Override
protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int size = MeasureSpec.getSize(widthMeasureSpec);
    int finalWidth = size + getPaddingLeft() + getPaddingRight();
    int finalHeight = strokeWidth + getPaddingBottom() + getPaddingTop();
    setMeasuredDimension(finalWidth, finalHeight);
}

寬度取測量值:xml 裡寫 match_parent 或 wrap_content 時,MeasureSpec.getSize() 返回父容器可用最大值;寫具體 dp 則返回該值。

高度直接取 strokeWidth。這意味著xml 中的 layout_height 無論寫什麼都不生效——這是設計上的取捨,進度條本來就該是細長的。

2.4 重寫 onDraw

繪製順序很重要:

1. 先畫一條橫線作為背景
2. 在背景上畫進度(onDraw 被反覆調用,視覺上進度就在移動)
3. 最後畫分隔線

為什麼分隔線要放最後?如果先畫分隔線,後畫的進度條會把它蓋住。順序必須這樣排。

先看背景線:

// 起始 X、Y 坐標
marginXY = strokeWidth / 2;
canvas.drawLine(marginXY, marginXY, getWidth() - marginXY, marginXY,
        progressbarBackgroundPaint);

marginXY 到底是什麼?看圖就清楚了:

strokeWidth 默認 20,一半就是 10,也就是 marginXY。由於 setStrokeCap(ROUND),線段的起點並不是黑色那個點,而是紅色點——也就是第一個圓的圓心;終點則是黃色點,是最後一個圓的圓心。所以要畫出完整的兩端半圓,起點要往右挪 marginXY,終點要往左挪 marginXY。

(可以這樣理解:整條進度條是 N 個緊密相連的圓拼成的,紅點與黃點分别是首末兩圓的圓心。這是個人推測,沒看源碼。)

接著畫進度:

if (startDrawProgress) {
    canvas.drawLine(marginXY, marginXY, getProgress(), marginXY, progressbarPaint);
}

startDrawProgress 默認 false,避免控件初始化時系統調用 onDraw 就把進度畫出來——那時候視頻還沒點播放,畫出來沒有意義。點擊播放後,通過對外方法把它置為 true。

最後是分隔線,這部分 coordinates 的計算反覆調了好幾輪,值得細說:

int separtatedLineX = 0;
for (int i = 0; i < videoSum - 1; i++) {
    separtatedLineX += (getWidth() - 2 * marginXY) / videoSum;
    canvas.drawLine(
        marginXY + separtatedLineX - (separtatedLineWidth / 2), marginXY,
        marginXY + separtatedLineX + (separtatedLineWidth / 2), marginXY,
        separtatedPaint);
}

調試過程中的三次嘗試:

第一次,直接用 canvas.drawLine(separtatedLineX, ...):

整體明顯偏左。原因是計算 separtatedLineX 時減掉了兩端的 marginXY,畫的時候卻沒加回來。

第二次,加上 marginXY:

偏差小了,但還是沒對齊。

第三次,分析坐標構成:

綠色是 marginXY,黑色是 separtatedLineX,兩者相加得到紅點橫坐標;再加 separtatedLineWidth 得到藍點橫坐標。問題在於——紅點應該落在分隔線的中間,而不是左端:

所以還要往左偏移半個分隔線寬度,即 separtatedLineWidth / 2:

canvas.drawLine(
    marginXY + separtatedLineX - (separtatedLineWidth / 2), marginXY,
    marginXY + separtatedLineX + (separtatedLineWidth / 2), marginXY,
    separtatedPaint);

這下完美對齊:

三、CustomProgressRunnable:進度計算與線程控制

在 CustomProgress 內部定義一個實現 Runnable 的內部類,負責計算進度並驅動繪製。

3.1 成員變量

private Handler handler;
private Thread thread;
private VideoView videoView;
private int perVideoLength;        // 每段視頻佔的進度條長度
private int currentVideoIndex;     // 當前視頻下標,從 0 開始
private boolean running = false;   // 線程運行標記
private boolean waiting = false;   // 線程等待(暫停)標記

running 與 waiting 這兩個布爾值是整個線程控制的基礎。

3.2 構造方法

public CustomProgressRunnable(Handler handler, VideoView videoView, int currentVideoIndex) {
    this.handler = handler;
    this.currentVideoIndex = currentVideoIndex;
    this.perVideoLength = (getWidth() - 2 * marginXY) / videoSum;
    this.videoView = videoView;
    thread = new Thread(this);
    // 設置進度條最大值:當前段之前的所有段 + 當前段
    setMax((currentVideoIndex + 1) * perVideoLength + marginXY);
}

綠色線段就是 perVideoLength:

播放第一個視頻時 currentVideoIndex 為 0,setMax 的结果就是第一段的終點:

第二、第三段同理。

3.3 線程主體與暫停邏輯

@Override
public void run() {
    // 當前視頻的起始坐標
    int currentVideoStartPosition = currentVideoIndex * perVideoLength;

    while (currentVideoStartPosition < getMax()) {
        synchronized (this) {
            if (!running) {
                break;              // 非運行狀態,退出循環
            }
            if (waiting) {
                try {
                    this.wait();    // 暫停,直到被喚醒
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        execute(currentVideoStartPosition);
    }
}

用 wait()/notifyAll() 實現暫停而非忙等,是這段代碼的關鍵——暫停期間線程真正讓出 CPU。

3.4 進度換算

public void execute(int currentVideoStartPosition) {
    if (running && !waiting) {
        int videoDuration = videoView.getDuration();
        if (videoDuration != -1) {
            // 1. 視頻播放比例
            float proportion = (float) videoView.getCurrentPosition() / (float) videoDuration;
            // 2. 換算成該段內的偏移
            int currentVideoPosition = (int) (proportion * perVideoLength);
            // 3. 加上段起始坐標與端部留白
            int newestVideoPosition = currentVideoPosition + currentVideoStartPosition + marginXY;

            handler.sendMessage(Message.obtain(handler, newestVideoPosition));
        }
    }
}

以第一個視頻為例,總時長 1000ms、當前播放 500ms:

* 比例 = 500/1000 = 50%
* 該段偏移 = 50% × 綠色線長度
* 最終坐標 = 段起始坐標(0) + 該段偏移 + marginXY

由於 execute 在 while 循環裡,只要條件成立它就會被不斷調用,進度條也就持續前進。

3.5 主線程接收

class TestHandler extends Handler {
    @Override
    public void handleMessage(Message msg) {
        int temp = msg.what;
        // setProgress 內部會觸發 onDraw,進度條隨之更新
        setProgress(temp);
    }
}

3.6 對外提供線程操作

public void start() {
    running = true;
    executorService.execute(thread);
}

public void suspend() {
    if (waiting) return;
    synchronized (this) { this.waiting = true; }
}

public void resume() {
    if (!waiting) return;
    synchronized (this) {
        this.waiting = false;
        this.notifyAll();
    }
}

public void stop() {
    if (!running) return;
    synchronized (this) { running = false; }
}

四、在 CustomProgress 中二次封裝

內部類具備了操作線程的能力,但對外調用還是不夠方便。在 CustomProgress 裡再包一層:

/** 開始進度條 */
public void startProgress(VideoView videoView, int currentVideoIndex) {
    if (currentVideoIndex > videoSum) {
        Log.e("--->", "當前視頻下標不能大於視頻總數");
        return;
    }
    customProgressBarRunnable =
            new CustomProgressBarRunnable(new TestHandler(), videoView, currentVideoIndex);
    customProgressBarRunnable.start();
    startDrawProgress = true;
}

public void hangUpThread() {
    if (customProgressBarRunnable == null) return;
    customProgressBarRunnable.suspend();
}

public void recoverThread() {
    if (customProgressBarRunnable == null) return;
    customProgressBarRunnable.resume();
}

public void stopThread() {
    if (customProgressBarRunnable == null) return;
    customProgressBarRunnable.stop();
}

/** 關閉線程池 */
public void closeThreadPool() {
    executorService.shutdown();
}

五、控件使用

5.1 佈局文件

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:background="#F2F2F2"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:orientation="vertical">

    <VideoView
        android:id="@+id/video_view"
        android:layout_centerHorizontal="true"
        android:layout_gravity="center_horizontal"
        android:layout_height="200dp"
        android:layout_width="match_parent" />

    <TextView
        android:id="@+id/txt_video_number"
        android:layout_gravity="center_horizontal"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="1/3"
        android:textSize="14dp" />

    <!-- 自定義控件必須寫全包名 -->
    <per.edward.ui.CustomProgressBar
        android:id="@+id/progressbar"
        android:layout_height="wrap_content"
        android:layout_width="match_parent" />

    <RelativeLayout
        android:layout_height="wrap_content"
        android:layout_width="match_parent">

        <ImageView
            android:id="@+id/image_prev_video"
            android:layout_centerVertical="true"
            android:layout_height="50dp"
            android:layout_marginRight="30dp"
            android:layout_toLeftOf="@+id/image_play_stop"
            android:layout_width="50dp"
            android:onClick="onClick"
            android:src="@mipmap/video_left" />

        <ImageView
            android:id="@+id/image_play_stop"
            android:layout_centerInParent="true"
            android:layout_height="100dp"
            android:layout_width="100dp"
            android:onClick="onClick"
            android:src="@mipmap/video_play" />

        <ImageView
            android:id="@+id/image_netx_video"
            android:layout_centerVertical="true"
            android:layout_height="50dp"
            android:layout_marginLeft="30dp"
            android:layout_toRightOf="@+id/image_play_stop"
            android:layout_width="50dp"
            android:onClick="onClick"
            android:src="@mipmap/video_right" />
    </RelativeLayout>
</LinearLayout>

xml 預覽:

在 xml 中使用自定義控件,標籤名必須是完整包名 + 類名:

另外要注意,CustomProgressBar 繼承自 ProgressBar,默認外觀是圓形的。想讓它表現為水平形式,需要加 style="?android:attr/progressBarStyleHorizontal"。

5.2 準備視頻資源

在 res 下新建 raw 文件夾,把 mp4 等視頻放進去:

Android 原生支持 MP4、3GP 等常見格式,遇到不支持的用轉碼軟件轉一下即可。

5.3 MainActivity

public class MainActivity extends Activity {

    private VideoView videoView;
    private ArrayList<String> videoUriList;
    private CustomProgressBar progressBar;
    private ImageView imagePlayStop;
    private TextView txtVideoNumber;

    private int currentVideoIndex = 0;
    private boolean isOpenVideoThread = false;
    private CustomProgressBar.CustomProgressBarRunnable customProgressBarRunnable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        videoView = findViewById(R.id.video_view);
        progressBar = findViewById(R.id.progressbar);
        imagePlayStop = findViewById(R.id.image_play_stop);
        txtVideoNumber = findViewById(R.id.txt_video_number);

        initData();
        setCallBackListener();
    }

    public void initData() {
        int[] videosId = {R.raw.bbb, R.raw.aaa, R.raw.ccc};
        for (int i = 0; i < videosId.length; i++) {
            videoUriList.add("android.resource://" + getPackageName() + "/" + videosId[i]);
        }
        progressBar.setVideoSum(videoUriList.size());
        txtVideoNumber.setText(1 + "/" + videoUriList.size());
    }

    public void setCallBackListener() {
        videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                progressBar.stopThread();
                ++currentVideoIndex;

                if (currentVideoIndex > videoUriList.size() - 1) {
                    Toast.makeText(MainActivity.this, "沒有視頻了", Toast.LENGTH_LONG).show();
                    imagePlayStop.setImageResource(R.mipmap.video_play);
                    currentVideoIndex = 0;
                    isOpenVideoThread = false;
                } else {
                    openVideoThread(currentVideoIndex);
                    txtVideoNumber.setText(currentVideoIndex + 1 + "/" + videoUriList.size());
                }
            }
        });

        videoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                Toast.makeText(MainActivity.this, "視頻播放錯誤!", Toast.LENGTH_LONG).show();
                return false;
            }
        });
    }

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.image_play_stop:
                imagePlayStop();
                break;

            case R.id.image_netx_video:
                ++currentVideoIndex;
                if (currentVideoIndex > videoUriList.size() - 1) {
                    Toast.makeText(MainActivity.this, "沒有視頻了", Toast.LENGTH_LONG).show();
                    currentVideoIndex = videoUriList.size() - 1;
                } else {
                    isOpenVideoThread = false;
                    progressBar.stopThread();
                    imagePlayStop.setImageResource(R.mipmap.video_stop);
                    txtVideoNumber.setText(currentVideoIndex + 1 + "/" + videoUriList.size());
                    openVideoThread(currentVideoIndex);
                }
                break;

            case R.id.image_prev_video:
                --currentVideoIndex;
                if (currentVideoIndex < 0) {
                    Toast.makeText(MainActivity.this, "沒有視頻了", Toast.LENGTH_LONG).show();
                    ++currentVideoIndex;
                } else {
                    isOpenVideoThread = false;
                    progressBar.stopThread();
                    imagePlayStop.setImageResource(R.mipmap.video_stop);
                    txtVideoNumber.setText(currentVideoIndex + 1 + "/" + videoUriList.size());
                    openVideoThread(currentVideoIndex);
                }
                break;
        }
    }

    /** 播放 / 暫停 */
    public void imagePlayStop() {
        txtVideoNumber.setText(currentVideoIndex + 1 + "/" + videoUriList.size());

        if (!isOpenVideoThread) {
            imagePlayStop.setImageResource(R.mipmap.video_stop);
            openVideoThread(currentVideoIndex);
        } else {
            customProgressBarRunnable = progressBar.getCustomProgressBarRunnable();
            if (!customProgressBarRunnable.isWaiting()) {
                progressBar.hangUpThread();     // 掛起進度條線程
                videoView.pause();
                imagePlayStop.setImageResource(R.mipmap.video_play);
            } else {
                progressBar.recoverThread();    // 恢復進度條線程
                videoView.start();
                imagePlayStop.setImageResource(R.mipmap.video_stop);
            }
        }
    }

    public void openVideoThread(int currentVideoIndex) {
        isOpenVideoThread = true;
        videoView.setVideoURI(Uri.parse(videoUriList.get(currentVideoIndex)));
        videoView.start();
        progressBar.startProgress(videoView, currentVideoIndex);
    }

    @Override
    protected void onPause() {
        CustomProgressBar.CustomProgressBarRunnable r = progressBar.getCustomProgressBarRunnable();
        // 退到桌面、鎖屏、跳轉頁面時自動暫停
        if (r != null && !r.isWaiting()) {
            imagePlayStop();
        }
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        progressBar.closeThreadPool();   // 關閉線程池
        progressBar.stopThread();
        super.onDestroy();
    }
}

生命週期方法的處理值得強調:

* onPause——從當前頁面退回桌面、鎖屏、跳轉到其他 Activity 時觸發,暫停視頻並掛起線程;
* onDestroy——頁面銷毀時關閉線程池並停止線程。

這兩處如果不處理,會出現「頁面都關了但音樂還在響」或者線程洩漏的問題。

最終效果:

六、總結

這個控件看下來,真正的收穫有三點:

1. 自定義 View 的三板斧——onMeasure 定尺寸、onDraw 畫圖形、自定義屬性通過 TypedArray 讀取;
2. 進度換算的本質是比例問題——視頻當前位置除以總時長得到比例,再乘以該段在進度條上的長度,最後加上段偏移;
3. 線程暫停用 wait/notify 而非標記位空轉——用 waiting 標記配合 wait(),暫定期間線程真正釋放 CPU。

另外,分隔線對齊那段反覆折騰也說明一件事:Canvas 繪製時,凡是帶寬度的圖形都要想清楚「坐標指的是左端還是中心」。想明白這一點,能省下大量試錯時間。

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