最近要支持一个视频挑战的活动,要求 WebView 能全屏播放视频,现在把 Android 端实现的方法分享给大家。
要实现全屏需要给 WebView 设置 WebChromeClient
并覆写 onShowCustomView
和 onHideCustomView()
两方法:
webView.setWebChromeClient(new WebChromeClient() {
@Override
public void onShowCustomView(View view, CustomViewCallback callback) {
// 此处的 view 就是全屏的视频播放界面,需要把它添加到我们的界面上
}
@Override
public void onHideCustomView() {
// 退出全屏播放,我们要把之前添加到界面上的视频播放界面移除
}
});
为了实现全屏的效果,需要将视频界面添加我们界面的最上层,有两种方式,一种是添加到 ContentView
中,核心代码如下:
contentParentView = findViewById(android.R.id.content);
webView.setWebChromeClient(new WebChromeClient() {
@Override
public void onShowCustomView(View view, CustomViewCallback callback) {
contentParentView.addView(view);
}
@Override
public void onHideCustomView() {
contentParentView.removeView(fullScreenView);
}
});
另一种是添加到 WindowManager
中,完整代码如下:
public class WebActivity extends AppCompatActivity {
...
private WindowManager windowManager;
private View fullScreenView = null;
@Override
protected void onResume() {
super.onResume();
// 如果之前处于全屏状态,重新进入后需要再次调用全屏
if (fullScreenView != null) fullScreen(fullScreenView);
}
@Override
public void onBackPressed() {
// 全屏状态点击返回退出全屏
if (fullScreenView != null) {
windowManager.removeViewImmediate(fullScreenView);
fullScreenView = null;
} else {
super.onBackPressed();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_webview);
windowManager = getWindowManager();
webView.setWebChromeClient(new WebChromeClient() {
@Override
public void onShowCustomView(View view, CustomViewCallback callback) {
// 此处的 view 就是全屏的视频播放界面,需要把它添加到我们的界面上
windowManager.addView(view, new WindowManager.LayoutParams(WindowManager.LayoutParams.TYPE_APPLICATION));
// 去除状态栏和导航按钮
fullScreen(view);
fullScreenView = view;
}
@Override
public void onHideCustomView() {
// 退出全屏播放,我们要把之前添加到界面上的视频播放界面移除
windowManager.removeViewImmediate(fullScreenView);
fullScreenView = null;
}
});
}
private void fullScreen(View view) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
} else {
view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
}
}
}