I know this is an old question and it was asked many times. But I tried many solutions they don't work with me.
I tested it in my Huawei 6P and Samsung S7, Nexus 5, the video(https://www.youtube-nocookie.com/embed/M68lNfqmTNk?rel=0&rel=0&showinfo=0) in WebView doesn't work as expected(it worked last year.). When I click the fullscreen button, "onShowCustomView" and "onHideCustomView" are invoked continuously. So I can see the video flashed(non-fullscreen -> full-screen -> non-fullscreen). Sometimes if I am lucky, the video goes full-screen mode, but if press full-screen button to exit fullscreen mode, the button doesn't work at all.
I wrote a demo in GitHub, hope anyone can help me. thanks.
Here is the code
Init Webview:
mWebView = (WebView)findViewById(R.id.webview);
mWebChromeClient = new MyWebChromeClient();
mWebView.setWebChromeClient(mWebChromeClient);
mWebView.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
mWebView.loadUrl(url);
return true;
}
});
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setUseWideViewPort(true);
webSettings.setAllowFileAccess(true);
webSettings.setSupportZoom(true);
webSettings.setLoadWithOverviewMode(true);
webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
MyWebChromeClient:
public class MyWebChromeClient extends WebChromeClient {
FrameLayout.LayoutParams LayoutParameters = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
@Override
public void onShowCustomView(View view, CustomViewCallback callback) {
Log.d("youtube", "onShowCustomView");
// if a view already exists then immediately terminate the new one
if (mCustomView != null) {
callback.onCustomViewHidden();
return;
}
mContentView = (ConstraintLayout) findViewById(R.id.activity_main);
mContentView.setVisibility(View.GONE);
mCustomViewContainer = new FrameLayout(MainActivity.this);
mCustomViewContainer.setLayoutParams(LayoutParameters);
mCustomViewContainer.setBackgroundResource(android.R.color.black);
view.setLayoutParams(LayoutParameters);
mCustomViewContainer.addView(view);
mCustomView = view;
mCustomViewCallback = callback;
mCustomViewContainer.setVisibility(View.VISIBLE);
setContentView(mCustomViewContainer);
}
@Override
public void onHideCustomView() {
Log.d("youtube", "onHideCustomView");
if (mCustomView == null) {
return;
} else {
// Hide the custom view.
mCustomView.setVisibility(View.GONE);
// Remove the custom view from its container.
mCustomViewContainer.removeView(mCustomView);
mCustomView = null;
mCustomViewContainer.setVisibility(View.GONE);
mCustomViewCallback.onCustomViewHidden();
// Show the content view.
mContentView.setVisibility(View.VISIBLE);
setContentView(mContentView);
}
}
}
I did set android:hardwareAccelerated in AndroidManifest.xml
android:hardwareAccelerated="true"