2018年11月12日 星期一

[Android] WebView內嵌Youtube無法全螢幕的解決方式

開發WebView的時候,卻發現,網頁上如果有 Youtube的影片,可以正常播放,但卻無法全螢幕,找了許久,找到了解法。







.java

 FrameLayout mVideoView; //將播放影片的View丟到LrameLayout來實現全螢幕效果 private View mCustomView; //用於存放目前影片的View WebChromeClient.CustomViewCallback customViewCallback;

mWebView.setWebChromeClient(new MyWebChromeClient());

class MyWebChromeClient extends WebChromeClient {
    @Override
    public void onShowCustomView(View view, int requestedOrientation,
        CustomViewCallback callback) {
        onShowCustomView(view, callback);
    }

    @Override
    public void onShowCustomView(View view,CustomViewCallback callback) {
        if (mCustomView != null) {
            callback.onCustomViewHidden();
            return; 
        }
        mCustomView = view;
        mWebView.setVisibility(View.GONE);
        mVideoView.setVisibility(View.VISIBLE);
        mVideoView.addView(view);
        customViewCallback = callback;
        hideSystemUI();
    }
    @Override
    public void onHideCustomView() {
        super.onHideCustomView();
        if (mCustomView == null) return;

        mWebView.setVisibility(View.VISIBLE);
        mVideoView.setVisibility(View.GONE);
        // Hide the custom view. 
        mCustomView.setVisibility(View.GONE);

        // Remove the custom view from its container.
        mVideoView.removeView(mCustomView);
        customViewCallback.onCustomViewHidden();
        showSystemUI();
        mCustomView = null;
    } 
}

//若改Activity被設成垂直顯示時,執行全螢幕將改為水平呈現。
private void hideSystemUI() {
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
    View decorView = getWindow().getDecorView();
    decorView.setSystemUiVisibility( View.SYSTEM_UI_FLAG_IMMERSIVE
        | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
        | View.SYSTEM_UI_FLAG_FULLSCREEN
    );
}

.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorMaster">

    <WebView
        android:id="@+id/webView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
    <FrameLayout
        android:id="@+id/video_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:visibility="gone" />
</android.support.constraint.ConstraintLayout>