問題
需求說偎箫,在豎屏WebView中橫屏視頻全屏展示箱亿,空白區(qū)域太大(或者相反)寒砖。
想讓橫屏視頻在全屏?xí)r橫屏展示费韭,豎屏視頻在全屏?xí)r豎屏展示谴返,以保證最大視頻展示區(qū)域赖晶。
解決
視頻全屏展示時的方向巾兆,可根據(jù) 重力感應(yīng) 自動調(diào)整
1. 設(shè)置頁面方向隨重力感應(yīng)自適應(yīng)變化
(context as? Activity)?.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR
代碼詳情
/**
* 顯示自定義控件
*/
private fun showCustomView(view: View?, callback: WebChromeClient.CustomViewCallback?) {
if (fullscreenContainer != null) {
callback?.onCustomViewHidden()
return
}
fullscreenContainer = FrameLayout(context).apply { setBackgroundColor(Color.BLACK) }
customViewCallback = callback
fullscreenContainer?.addView(view)
val decorView = (context as? Activity)?.window?.decorView as? FrameLayout
(context as? Activity)?.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR
systemUiVisibility =
View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or
View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or View.SYSTEM_UI_FLAG_IMMERSIVE or
View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
decorView?.addView(fullscreenContainer)
}
2. 在退出全屏?xí)r如捅,將屏幕方向改為原來頁面方向(即最初WebView所在的頁面方向)
此處是豎屏
(context as? Activity)?.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT
代碼詳情
/**
* 隱藏自定義控件
*/
private fun hideCustomView() {
if (fullscreenContainer == null) {
return
}
val decorView = (context as? Activity)?.window?.decorView as? FrameLayout
(context as? Activity)?.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT
fullscreenContainer?.removeAllViews()
decorView?.removeView(fullscreenContainer)
systemUiVisibility = View.SYSTEM_UI_FLAG_VISIBLE
fullscreenContainer = null
customViewCallback?.onCustomViewHidden()
customViewCallback = null
}
上述兩個方法都是 WebView 的方法
webChromeClient = object : WebChromeClient() {
override fun onShowCustomView(view: View?, callback: CustomViewCallback?) {
super.onShowCustomView(view, callback)
showCustomView(view, callback)
}
override fun onHideCustomView() {
super.onHideCustomView()
hideCustomView()
}
}
3. 設(shè)置當(dāng)前頁面所在的 Activity 同欠,屏幕方向改變時样傍,不重走生命周期方法
這一步至關(guān)重要!铺遂!在 AndroidManifest.xml 中設(shè)置如下
android:configChanges="orientation|keyboardHidden|screenSize"
即
<activity
android:name="com.*.*.*.*.*.ArrangeActivity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:screenOrientation="portrait" />
注意
退出全屏?xí)r衫哥,若想上一頁面屏幕方向和進(jìn)入全屏前一致,需要設(shè)置:
// 上一頁面 橫屏
(context as? Activity)?.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
// 上一頁面 豎屏
(context as? Activity)?.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT
設(shè)置成 SENSOR 襟锐, 而不是 REVERSE
ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE
// 或
ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT
設(shè)置成 REVERSE 撤逢,會根據(jù)全屏?xí)r最終旋轉(zhuǎn)的方向來判斷,則有可能導(dǎo)致 視頻是倒著的,或者整個頁面翻轉(zhuǎn)了 180 度蚊荣。