需要以下代码来显示由 web 核心框架启动的视频播放器。整个流程的关键是 VideoView 被传递回 WebChromeClient 并且您需要将该视图附加到您的视图层次结构中。
我通过查看作为 AOSP 的一部分提供的浏览器源代码来组装它。
此代码引用了 4 个可能不明显的视图。视图层次结构是:
FrameLayout mContentView
(根)
WebView mWebView
(mContentView 的子级)
FrameLAyout mCustomViewContainer
(mContentView 的子级)
View mCustomView
(mCustomViewContainer 的子级)
视图被配置为设置容器活动的一部分。
<FrameLayout
android:id="@+id/fullscreen_custom_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FF000000"/>
<FrameLayout
android:id="@+id/main_content"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" >
<WebView
android:id="@+id/webView"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</FrameLayout>
</FrameLayout>
在您的活动中onCreate
:
mContentView = (FrameLayout) findViewById(R.id.main_content);
mWebView = (WebView) findViewById(R.id.webView);
mCustomViewContainer = (FrameLayout) findViewById(R.id.fullscreen_custom_content);
注册一个WebChromeClient
。mWebView
该客户端应覆盖以下 2 - 4 个方法:
void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback)
{
// if a view already exists then immediately terminate the new one
if (mCustomView != null)
{
callback.onCustomViewHidden();
return;
}
// Add the custom view to its container.
mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
mCustomView = view;
mCustomViewCallback = callback;
// hide main browser view
mContentView.setVisibility(View.GONE);
// Finally show the custom view container.
mCustomViewContainer.setVisibility(View.VISIBLE);
mCustomViewContainer.bringToFront();
}
void onHideCustomView()
{
if (mCustomView == null)
return;
// Hide the custom view.
mCustomView.setVisibility(View.GONE);
// Remove the custom view from its container.
mCustomViewContainer.removeView(mCustomView);
mCustomView = null;
mCustomViewContainer.setVisibility(View.GONE);
mCustomViewCallback.onCustomViewHidden();
// Show the content view.
mContentView.setVisibility(View.VISIBLE);
}
public Bitmap getDefaultVideoPoster()
{
if (mDefaultVideoPoster == null)
{
mDefaultVideoPoster = BitmapFactory.decodeResource(getResources(), R.drawable.default_video_poster);
}
return mDefaultVideoPoster;
}
public View getVideoLoadingProgressView()
{
if (mVideoProgressView == null)
{
LayoutInflater inflater = LayoutInflater.from(this);
mVideoProgressView = inflater.inflate(R.layout.video_loading_progress, null);
}
return mVideoProgressView;
}
您可能还想添加活动生命周期绑定,例如:
@Override
protected void onStop()
{
super.onStop();
if (mCustomView != null)
{
if (mCustomViewCallback != null)
mCustomViewCallback.onCustomViewHidden();
mCustomView = null;
}
}
@Override
public void onBackPressed()
{
if (mCustomView != null)
{
onHideCustomView();
} else
{
finish();
}
}
到您的活动,以在活动停止或按下后退按钮时隐藏视频。