Android原生API提供了WebView来加载H5网页,H5网页中可能使用Video标签实现视频播放,正常播放比较好实现,但是一般来说视频都会要求全屏播放,这怎么弄呢?下面就来实现一下。
整体思路:
点击Video标签全屏播放按钮时,会回调WebChromeClient的onShowCustomView()方法,退出全屏时会回调onHideCustomView()方法,所以思路就来了,onShowCustomView()中将手机屏幕设置为横屏,将WebView以及其他控件隐藏并将视频控件占满整个屏幕即可;onHideCustomView()中将手机屏幕设置为竖屏,将视频控件隐藏,再次重新显示WebView
关键代码实现:
/**
* 实现Video标签全屏播放
*/
lateinit var mCustomView: View
lateinit var mParent: ViewGroup
override fun onShowCustomView(view: View, callback: WebChromeClient.CustomViewCallback?) {
setScreen()
var parent: ViewGroup = mWebActWebContainer.parent as ViewGroup
parent.removeView(mWebActWebContainer)
parent.addView(view)
mCustomView = view
mParent = parent;
}
override fun onHideCustomView() {
setScreen()
mParent.removeView(mCustomView)
mParent.addView(mWebActWebContainer)
}
private fun setScreen() {
if (resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT) {
requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
} else {
requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
}
}
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
when (newConfig.orientation) {
Configuration.ORIENTATION_LANDSCAPE -> {
window.clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
Configuration.ORIENTATION_PORTRAIT -> {
window.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
window.addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
}
}
}
代码逻辑比较简单,按照上述思路一步步走就ok了,需要注意的是WebView中播放视频一般要开启硬件加速!
横屏.PNG这是我的实现截图:
[图片上传中...(横屏.PNG-123245-1571124196282-0)]
读者有不明白之处请留言交流,觉得凑活就给点个赞吧!
网友评论