webview播放视频并且点击全屏横屏的方法
- 首先initWebView,好吧有点多,有些是项目里其他需求需要的,不要在意这些细节···
1 | public static void initWebView(WebView webView) { |
- 设置webviewclient,在当前的webview加载新的url,不设置的话会打开一个浏览器的
1 | web.setWebViewClient(new WebViewClient() { |
- 设置webChromeClient
1 | web.setWebChromeClient(new WebChromeClient() { |
全屏其实就是获取decorView,重新绘制一个全屏的framelayout盖在原有界面上,下面是一些方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71/**
* 视频播放全屏
**/
private void showCustomView(View view, WebChromeClient.CustomViewCallback callback) {
// if a view already exists then immediately terminate the new one
if (customView != null) {
callback.onCustomViewHidden();
return;
}
setStatusBarVisibility(false);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
web.setVisibility(View.INVISIBLE);
FrameLayout decor = (FrameLayout) getWindow().getDecorView();
fullscreenContainer = new FullscreenHolder(mContext);
fullscreenContainer.addView(view, COVER_SCREEN_PARAMS);
decor.addView(fullscreenContainer, COVER_SCREEN_PARAMS);
customView = view;
customViewCallback = callback;
}
/**
* 隐藏视频全屏
*/
private void hideCustomView() {
if (customView == null) {
return;
}
setStatusBarVisibility(true);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
FrameLayout decor = (FrameLayout) getWindow().getDecorView();
decor.removeView(fullscreenContainer);
fullscreenContainer = null;
customView = null;
customViewCallback.onCustomViewHidden();
web.setVisibility(View.VISIBLE);
}
/**
* 全屏容器界面
*/
static class FullscreenHolder extends FrameLayout {
public FullscreenHolder(Context ctx) {
super(ctx);
setBackgroundColor(ctx.getResources().getColor(android.R.color.black));
}
public boolean onTouchEvent(MotionEvent evt) {
return true;
}
}
private void setStatusBarVisibility(boolean visible) {
int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
public void onBackPressed() {
/** 回退键 事件处理 优先级:视频播放全屏-网页回退-关闭页面 */
if (customView != null) {
hideCustomView();
} else if (web.canGoBack()) {
web.goBack();
} else {
super.onBackPressed();
}
}最后不要忘了
1 |
|
以及在清单中加上
1 | <activity android:name=".activity.WebActivity" |
不开硬件加速,视频会黑屏,有声音没图像;
不设置configChanges,当转屏以及转屏造成的屏幕尺寸变化的时候,activity会冲走onCreate方法,前面干的所有事儿都白干了~
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 七夜的小屋!