Android uses WebView to realize full screen switching and playing web video function

  • 2021-11-10 10:48:56
  • OfStack

First write the layout file activity_main. xml:


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:id="@+id/container"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:orientation="vertical">
  <FrameLayout
    android:id="@+id/video_view"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:visibility="gone"
    ></FrameLayout>
  <Button
    android:id="@+id/video_landport"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text=" If the button is not displayed in full screen, click to switch the horizontal screen "
    android:gravity="center"
    />
  <WebView
    android:id="@+id/video_webview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    />
  </LinearLayout>

Principle: When realizing full screen, put the video in webview into an View (video_view control in the layout), and then hide webview! In this way, full-screen playback is realized!

Now let's take a concrete look at how to achieve it:

Put the code MainActivity. java first:


public class MainActivity extends Activity {
   private FrameLayout videoview;//  Video Load in Full Screen view
  private Button videolandport;
  private WebView videowebview;
  private Boolean islandport = true;//true Indicates that this is a vertical screen, false Indicates the horizontal screen at this time. 
  private View xCustomView;
  private xWebChromeClient xwebchromeclient;
  private String url = "http://look.appjx.cn/mobile_api.php?mod=news&id=12604";
  private WebChromeClient.CustomViewCallback   xCustomViewCallback;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);// Remove the application title 
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
        WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.activity_main);
    initwidget();
    initListener();
    videowebview.loadUrl(url);
  }
  private void initListener() {
    // TODO Auto-generated method stub
    videolandport.setOnClickListener(new Listener());
  }
  private void initwidget() {
    // TODO Auto-generated method stub
    videoview = (FrameLayout) findViewById(R.id.video_view);
    videolandport = (Button) findViewById(R.id.video_landport);
    videowebview = (WebView) findViewById(R.id.video_webview);
    WebSettings ws = videowebview.getSettings();
    /**
     * setAllowFileAccess  Enable or disable WebView Access file data  setBlockNetworkImage  Whether to display network images 
     * setBuiltInZoomControls  Sets whether zooming is supported  setCacheMode  Set the mode of buffering 
     * setDefaultFontSize  Set the default font size  setDefaultTextEncodingName  Set the default encoding to use when decoding 
     * setFixedFontFamily  Set fixed fonts for use  setJavaSciptEnabled  Set whether support Javascript
     * setLayoutAlgorithm  Set the layout mode  setLightTouchEnabled  Set the option to activate with the mouse 
     * setSupportZoom  Set whether zoom is supported 
     * */
    ws.setBuiltInZoomControls(true);//  Hide Zoom Button 
    ws.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);//  Typesetting adaptation screen 
    ws.setUseWideViewPort(true);//  Scalable to any scale 
    ws.setLoadWithOverviewMode(true);// setUseWideViewPort Method settings webview Recommended windows. setLoadWithOverviewMode The method is to set the webview The mode of the loaded page. 
    ws.setSavePassword(true);
    ws.setSaveFormData(true);//  Save form data 
    ws.setJavaScriptEnabled(true);
    ws.setGeolocationEnabled(true);//  Enable Geolocation 
    ws.setGeolocationDatabasePath("/data/data/org.itri.html5webview/databases/");//  Set the database path to locate 
    ws.setDomStorageEnabled(true);
    xwebchromeclient = new xWebChromeClient();
    videowebview.setWebChromeClient(xwebchromeclient);
    videowebview.setWebViewClient(new xWebViewClientent());
  }
  class Listener implements OnClickListener {
    @Override
    public void onClick(View v) {
      // TODO Auto-generated method stub
      switch (v.getId()) {
      case R.id.video_landport:
        if (islandport) {
          setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
          videolandport.setText(" If the button is not displayed in full screen, click to switch the horizontal screen ");
        }else {
          setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
          videolandport.setText(" If the button is not displayed in full screen, click to switch the vertical screen ");
        }
        break;
      default:
        break;
      }
    }
  }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
      if (keyCode == KeyEvent.KEYCODE_BACK) {
        if (inCustomView()) {
          hideCustomView();
          return true;
        }else {
        videowebview.loadUrl("about:blank");
//          mTestWebView.loadData("", "text/html; charset=UTF-8", null);
        MainActivity.this.finish();
          Log.i("testwebview", "===>>>2");
      }
      }
      return true;
    }
    /**
    *  Determine whether it is full screen 
    * @return
    */
    public boolean inCustomView() {
       return (xCustomView != null);
     }
     /**
     *  When full screen, press the Back Add key to exit the full screen method 
     */
     public void hideCustomView() {
       xwebchromeclient.onHideCustomView();
     }
  /**
   *  Deal with Javascript The dialog box, website icon, website title, and page loading progress of 
   * @author
   */
  public class xWebChromeClient extends WebChromeClient {
    private Bitmap xdefaltvideo;
    private View xprogressvideo;
    @Override
    // The method that full screen will be called when playing network video 
    public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback)
    {
      if (islandport) {
      }
      else{
//        ii = "1";
//        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
      }
      setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
      videowebview.setVisibility(View.GONE);
      // If 1 Views already exist, then terminate immediately and create a new one 1 A 
      if (xCustomView != null) {
        callback.onCustomViewHidden();
        return;
      }      
      videoview.addView(view);
      xCustomView = view;
      xCustomViewCallback = callback;
      videoview.setVisibility(View.VISIBLE);
    }
    @Override
    // Video playback exit full screen will be called 
    public void onHideCustomView() {
      if (xCustomView == null)// It is not in full screen playback status 
        return;           
      // Hide the custom view.
      setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
      xCustomView.setVisibility(View.GONE);
      // Remove the custom view from its container.
      videoview.removeView(xCustomView);
      xCustomView = null;
      videoview.setVisibility(View.GONE);
      xCustomViewCallback.onCustomViewHidden();
      videowebview.setVisibility(View.VISIBLE);
      //Log.i(LOGTAG, "set it to webVew");
    }
    // Add default icon to video load 
    @Override
    public Bitmap getDefaultVideoPoster() {
      //Log.i(LOGTAG, "here in on getDefaultVideoPoster"); 
      if (xdefaltvideo == null) {
        xdefaltvideo = BitmapFactory.decodeResource(
            getResources(), R.drawable.videoicon);
      }
      return xdefaltvideo;
    }
    // Video loading process loading
    @Override
    public View getVideoLoadingProgressView() {
      //Log.i(LOGTAG, "here in on getVideoLoadingPregressView");
      if (xprogressvideo == null) {
        LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
        xprogressvideo = inflater.inflate(R.layout.video_loading_progress, null);
      }
      return xprogressvideo;
    }
    // Web page title 
     @Override
     public void onReceivedTitle(WebView view, String title) {
      (MainActivity.this).setTitle(title);
     }
//     @Override
//    // When WebView Update window progress when progress changes 
//     public void onProgressChanged(WebView view, int newProgress) {
//       (MainActivity.this).getWindow().setFeatureInt(Window.FEATURE_PROGRESS, newProgress*100);
//     }   
  }
  /**
   *  Handle various notifications, requests and other events 
   * @author
   */
  public class xWebViewClientent extends WebViewClient {
     @Override
      public boolean shouldOverrideUrlLoading(WebView view, String url) {
        Log.i("webviewtest", "shouldOverrideUrlLoading: "+url);
        return false;
      }
  }
  /**
   *  This method is called when the horizontal and vertical screens are switched 
   * @author
   */
  @Override
  public void onConfigurationChanged(Configuration newConfig) {
    Log.i("testwebview", "=====<<< onConfigurationChanged >>>=====");
     super.onConfigurationChanged(newConfig);
     if(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE){
       Log.i("webview", "   Now it's a horizontal screen 1");
       islandport = false;
      }else if(newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
       Log.i("webview", "   Now it's a vertical screen 1");
       islandport = true;
      }
  }
}

Finally, talk about AndroidManifest. xml settings;
Access to the network with this sentence


<uses-permission android:name="android.permission.INTERNET"/>

In order not to call onCreate and other methods again when switching horizontal and vertical screens, add this sentence:

android:configChanges="orientation|keyboardHidden|screenSize"

Summarize

Above is this site to introduce you Android use WebView full-screen switching to play web video function, I hope to help you, if you have any questions welcome to leave me a message, this site will reply to you in time!


Related articles: