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

原生 VideoView 全屏播放時的問題與原理剖析

編輯:關於 Android 開發

之前上了一門課,其中一節講到用影片當作啟動畫面。講師用的是自訂 VideoView,重寫 onMeasure 方法,因為原生 VideoView 在那種情況下無法全屏播放。當時沒深入研究,現在補回來。

測試用的是 36 氪的影片(608×1080)與 Genymotion 中的 Google Nexus 5(1080×1920)。

一、效果對比

1. 原生 VideoView 的效果(這裡沒讓底部導航欄也變透明;由於截圖上很難看出差別,後面會解釋)。

xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <VideoView
        android:id="@+id/video_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clickable="false"
        android:focusable="false"
        android:focusableInTouchMode="false"/>
</LinearLayout>

java

public class VideoViewActivity extends AppCompatActivity {
    private VideoView mVideoView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_view);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        mVideoView = (VideoView) findViewById(R.id.video_view);
        mVideoView.setVideoURI(Uri.parse("android.resource://" + getPackageName()
                + "/" + R.raw.kr36));
        mVideoView.start();
        mVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                mVideoView.start();
            }
        });
    }
}

2. 自訂 VideoView 的效果

布局檔大致同上,僅改了控制項名稱與 id。Activity.java 也大致相同,這裡是自訂 VideoView 的程式碼,只重寫了 onMeasure:

public class CustomVideoView extends VideoView {
    public CustomVideoView(Context context) { super(context); }
    public CustomVideoView(Context context, AttributeSet attrs) { super(context, attrs); }
    public CustomVideoView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width = getDefaultSize(0, widthMeasureSpec);
        int height = getDefaultSize(0, heightMeasureSpec);
        setMeasuredDimension(width, height);
    }
}

二、先了解幾個關鍵

1. MeasureSpec 類別。程式碼不多卻很精妙,這裡只需理解它的三種 mode:

/**
 * 1、UNSPECIFIED:parent 不對 child 做限制,child 想要多大就给多大,
 *    一般極少用到,多為系統內部使用。
 * 2、EXACTLY:對應 match_parent 或指定具體數值。
 * 3、AT_MOST:對應 wrap_content。
 */
public static class MeasureSpec {
    private static final int MODE_SHIFT = 30;
    private static final int MODE_MASK = 0x3 << MODE_SHIFT;
    public static final int UNSPECIFIED = 0 << MODE_SHIFT;
    public static final int EXACTLY = 1 << MODE_SHIFT;
    public static final int AT_MOST = 2 << MODE_SHIFT;

    public static int getMode(int measureSpec) {
        return (measureSpec & MODE_MASK);
    }
    public static int getSize(int measureSpec) {
        return (measureSpec & ~MODE_MASK);
    }
}

本例中所有控制項的 width 與 height 都是 match_parent,因此以下分析都基於 MeasureSpec.EXACTLY。

2. getDefaultSize

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;
}

由於都是 EXACTLY,最終回傳的是 MeasureSpec.getSize(measureSpec),與第一個參數 size 無關。

3. setMeasuredDimension

protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
    boolean optical = isLayoutModeOptical(this);
    if (optical != isLayoutModeOptical(mParent)) {
        Insets insets = getOpticalInsets();
        int opticalWidth = insets.left + insets.right;
        int opticalHeight = insets.top + insets.bottom;
        measuredWidth += optical ? opticalWidth : -opticalWidth;
        measuredHeight += optical ? opticalHeight : -opticalHeight;
    }
    setMeasuredDimensionRaw(measuredWidth, measuredHeight);
}

中間的判斷涉及 ViewGroup 的 LayoutMode,有兩個值:預設值 clipBounds 會保留子 view 之間的留白(有些控制項看起來比實際小,但仍佔據給定大小,讓部分邊緣留白,避免子 view 真的黏在一起);另一個是 opticalBounds,用來消除 clipBounds 的效果。一般不會進入這個判斷區塊。真正要關注的是最後一句 setMeasuredDimensionRaw。

4. setMeasuredDimensionRaw

private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
    mMeasuredWidth = measuredWidth;
    mMeasuredHeight = measuredHeight;
    mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
}

這個方法把最終測量結果賦值給該 view 的全域變數,代表 measure 階段結束。

三、對比原生 VideoView 的 onMeasure

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int width = getDefaultSize(mVideoWidth, widthMeasureSpec);
    int height = getDefaultSize(mVideoHeight, heightMeasureSpec);

    if (mVideoWidth > 0 && mVideoHeight > 0) {
        int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);

        if (widthSpecMode == MeasureSpec.EXACTLY && heightSpecMode == MeasureSpec.EXACTLY) {
            // 尺寸固定
            width = widthSpecSize;
            height = heightSpecSize;
            // 依長寬比調整
            if (mVideoWidth * height < width * mVideoHeight) {
                width = height * mVideoWidth / mVideoHeight;
            } else if (mVideoWidth * height > width * mVideoHeight) {
                height = width * mVideoHeight / mVideoWidth;
            }
        } else if (widthSpecMode == MeasureSpec.EXACTLY) {
            ...
        } else if (heightSpecMode == MeasureSpec.EXACTLY) {
            ...
        } else {
            ...
        }
    } else {
        // 尚無尺寸,直接採用指定 spec 大小
    }
    setMeasuredDimension(width, height);
}

我在這個方法中印過 width 與 height 的值,它們就是螢幕顯示區域的解析度。也就是說,當狀態欄與底部導航欄都透明時,width 是 1080、height 是 1920,正好是 Nexus 5 的解析度;而當底部導航欄不透明時,height 就變成 1776。

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int width = getDefaultSize(0, widthMeasureSpec);
    int height = getDefaultSize(0, heightMeasureSpec);
    setMeasuredDimension(width, height);
}

現在對比原生的 onMeasure 來分析。首先透過 getDefaultSize 取得 width 與 height——前面說過,本例中它只與第二個參數有關,而這兩個參數都從相同的 ViewGroup 傳入,所以不論原生還是重寫,從 getDefaultSize 得到的值都一樣。接著進入第一層判斷區塊,用 getMode 與 getSize 再次取得 mode 與 size(其實 getDefaultSize 裡已做過,所以外層的 width 與 widthSpecSize 相同,height 亦然)。

由於本例進入的是第一個判斷區塊(兩者皆 EXACTLY),下面的判斷先省略。關鍵在於比較乘積後會修改 width 或 height,這正是原生與重寫效果不同的根源。程式邏輯很清晰,直接代入數值分析:影片幀寬 608、幀高 1080,測試機 1080×1920。

mVideoWidth × height = 608 × 1920 = 1,167,360;mVideoHeight × width = 1080 × 1080 = 1,166,400。因此修改的是 height,約等於 1918.4。這也解釋了為何開頭不讓底部導航欄透明——因為只差約兩個像素,截圖根本看不出來。而當底部導航欄不透明時,height 是 1776,這時修改的是 width,約等於 999.8,差異就明顯多了(如上圖)。

總的來說,這段程式碼把 VideoView 的寬或高依長寬比做了調整,而我指定的是 match_parent,理應就是螢幕顯示區域的大小;重寫的方法則跳過了這段邏輯,讓 VideoView 的寬高維持 match_parent。

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