嘿,这是一个老问题,但这是我更新的解决方案。我正在使用 Kotlin 和 AndroidX。
首先,您的“视频活动布局”中需要两个视图,如下所示:
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto">
<FrameLayout
android:id="@+id/videoFrame"
android:layout_width="0dp"
android:layout_height="0dp"
android:elevation="10dp" android:visibility="gone"
app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent">
</FrameLayout>
<WebView
android:id="@+id/webview"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" /></androidx.constraintlayout.widget.ConstraintLayout>
您将使用 videoFrame 框架布局来设置额外的全屏内容,并且显然为您的网络内容设置 webview。
然后,使用一种方法将 url 加载到您的 webview:
private fun initWebView(webUrl : String){
val webView : WebView? = this.findViewById(R.id.webview)
val videoFrame : FrameLayout? = this.findViewById(R.id.videoFrame)
webView?.settings?.apply {
mediaPlaybackRequiresUserGesture = true
javaScriptEnabled = true //use this carefully
}
webView?.webChromeClient = object : WebChromeClient () {
override fun onProgressChanged(view: WebView?, newProgress: Int) {
Log.d(TAG, "WebChromeClient, onProgressChanged newProgress=$newProgress") }
override fun onShowCustomView(fullScreenContent: View?, callback: CustomViewCallback?) {
super.onShowCustomView(fullScreenContent, callback)
Log.d(TAG, "onShowCustomView")
fullScreenContent?.let {fullScreenView ->
videoFrame?.removeAllViews()
videoFrame?.visibility = View.VISIBLE
videoFrame?.addView(fullScreenView)
}
}
override fun onHideCustomView() {
super.onHideCustomView()
Log.d(TAG, "onShowCustomView")
videoFrame?.visibility = View.GONE
videoFrame?.removeAllViews()
}
}
webView?.loadUrl(webUrl)
}
当您覆盖 onShowCustomView 和 onHideCustomView 方法时,魔法就会发生。
只需将 fullScreenContent 添加到 videoFrame 布局中。
仅此而已。
它在 Android 9 上运行(并经过测试)。