Some developers running Android OS may have encountered the problem of playing youtube videos in OS version 2.2 and later. When the old version using
shouldOverrideUrlLoading has stopped working, and new solutions are quite difficult to find. In this post, I offer an example based on using some of the features of
WebView associated with the dynamic creation of the so-called
CustomView .
Description of what is happening
To simplify work with video playback, Android developers
have already added the automatic creation of a streaming player with all the necessary parameters and a VideoView to display this stream. We, as developers, need only to correctly use all this wealth and properly dispose of it.
VideoView
After the user clicks on the preview in
WebView showing youtube mobile version:

')
WebView calls the
WebChromeClient object that contains the already running VideoView ready to be displayed on the screen, our task is to allow this View to display its content to the user. Therefore, in the
onShowCustomView method
, we receive and process this component by adding it to the current widget hierarchy.
@ Override <br/>
public void onShowCustomView ( View view, CustomViewCallback callback ) { <br/>
if ( mCustomView ! = null ) { <br/>
callback. onCustomViewHidden ( ) ; <br/>
} else { <br/>
mCustomView = view ; <br/>
mCustomViewCallback = callback ; <br/>
mWebView. setVisibility ( View . GONE ) ; <br/>
mMainContentContainer. addView ( view, CUSTOM_VIEW_LAYOUT_PARAMS ) ; <br/>
} <br/>
}
@ Override <br/>
public void onShowCustomView ( View view, CustomViewCallback callback ) { <br/>
if ( mCustomView ! = null ) { <br/>
callback. onCustomViewHidden ( ) ; <br/>
} else { <br/>
mCustomView = view ; <br/>
mCustomViewCallback = callback ; <br/>
mWebView. setVisibility ( View . GONE ) ; <br/>
mMainContentContainer. addView ( view, CUSTOM_VIEW_LAYOUT_PARAMS ) ; <br/>
} <br/>
}
But since we changed the current View, then to continue viewing the site, after watching the video or by clicking on the BACK button, we need to return the previous state of the hierarchy, another method from
WebChromeClient , namely
onHideCustomView , is used for this. In it, we close the VideoView and continue to show WebView.
@ Override <br/>
public void onHideCustomView ( ) { <br/>
if ( mCustomView ! = null ) { <br/>
mMainContentContainer. removeView ( mCustomView ) ; <br/>
mCustomViewCallback. onCustomViewHidden ( ) ; <br/>
mCustomView = null ; <br/>
mWebView. setVisibility ( View . VISIBLE ) ; <br/>
} <br/>
}
@ Override <br/>
public void onHideCustomView ( ) { <br/>
if ( mCustomView ! = null ) { <br/>
mMainContentContainer. removeView ( mCustomView ) ; <br/>
mCustomViewCallback. onCustomViewHidden ( ) ; <br/>
mCustomView = null ; <br/>
mWebView. setVisibility ( View . VISIBLE ) ; <br/>
} <br/>
}
These actions are quite enough to work with YouTube video on Android 2.2.
An example of a working project.