1、原理
利用 WebChromeClient 中的 onShowCustomView 和 onHideCustomView 方法来实现全屏功能
2、创建一个activity_web_view.xml 文件 里面放一个WebView 和 Fragment
<?xml version="1.0" encoding="UTF-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
tools:context=".ui.activity.WebViewActivity"
android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<WebView
android:layout_height="match_parent"
android:layout_width="match_parent"
app:layout_constraintVertical_bias="0.0"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintHorizontal_bias="0.0"
android:orientation="vertical"
android:id="@+id/view"/>
<FrameLayout
android:id="@+id/frameLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
3、创建一个WebViewActivity.java文件,获取WebView和Fragment,并实现WebView相关方法
public class WebViewActivity extends AppCompatActivity{
private View mCustomView;
private FrameLayout mFrameLayout;
private WebChromeClient.CustomViewCallback mCustomViewCallback;
private WebView mWebView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_view);
mWebView = findViewById(R.id.view);
mFrameLayout = findViewById(R.id.frameLayout);
setWebView();
//这里使用是腾讯视频的链接
mWebView.load("https://v.qq.com/x/cover/mzc00200k1qzwd5/k0046p8c271.html");
}
privte void setWebView(){
WebSettings webSettings = mWebView.getSettings();
//必须设置否则,无法执行js函数
webSettings.setJavaScriptEnabled(true);
mWebView.setWebChromeClient(new WebChromeClient() {
@Override
public void onShowCustomView(View view, CustomViewCallback callback) {
super.onShowCustomView(view, callback);
//点击视频中的全屏按钮,会执行当前方法
//然后将frameLayout显示隐藏WebView控件便可实现全屏,并横竖屏切换
if (mCustomView != null) {
callback.onCustomViewHidden();
return;
}
mCustomView = view;
mFrameLayout.addView(mCustomView);
mCustomViewCallback = callback;
setVisibility(View.GONE);
//切换横屏
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
@Override
public void onHideCustomView() {
setVisibility(View.VISIBLE);
//当退出全屏时会执行当前方法
//然后将frameLayout隐藏显示WebView就可以了,记得切换竖屏
if (mCustomView == null) {
return;
}
mCustomView.setVisibility(View.GONE);
mFrameLayout.removeView(mCustomView);
mCustomViewCallback.onCustomViewHidden();
mCustomView = null;
//切换竖屏
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
super.onHideCustomView();
}
}
}
}
4、横竖屏切换时处理状态栏
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {// 横屏
//状态栏沉浸式样式处理
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {// 竖屏
//状态栏默认样式处理
}
}