SoFunction
Updated on 2025-04-03

Detailed explanation of the usage of Android WebView components

This article describes the usage of Android WebView components. Share it for your reference, as follows:
If you want WebView to access the network, you must add permissions in it

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

Very simple, it's just a WebView

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:andro
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:orientation="vertical" >
  <WebView
    android:
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" />
</LinearLayout>

Code:

package ;
import ;
import ;
import ;
public class WebViewDemoActivity extends Activity {
  private WebView mWebView;
  @Override
  public void onCreate(Bundle savedInstanceState) {
    (savedInstanceState);
    setContentView();
    mWebView = (WebView) findViewById();
    // Get the WebSettings object and set the JavaScript parameters to support    // If the page you are visiting has JavaScript, the WebView must be set to support JavaScript, otherwise blank pages will be displayed    ().setJavaScriptEnabled(true);
    // Load URL    ("/");
  }
}

After running, you will see that the URL is loaded correctly.

But there is a problem. When you click on the link to continue browsing, the default Browser will pop up. In order to continue browsing in the WebView, you need to use the shouldOverrideUrlLoading method:

@Override
public void onCreate(Bundle savedInstanceState) {
  。。。。。。。。。。。。。。。。。。。。。。。。
  // Although the Google homepage is displayed in the WebView, if you click the link to continue browsing, it will be displayed in the system's default Browser  // In order to continue displaying in WebView, you need to rewrite the shouldOverrideUrlLoading method  (new MyWebViewClient());
  。。。。。。。。。。。。。。。。。。。。。。。。
    }
private class MyWebViewClient extends WebViewClient {
  @Override
  public boolean shouldOverrideUrlLoading(WebView view, String url) {
    (url);
    return true;
  }
}

In addition, if you want to press the fallback key to return to the previous page, then

/**
  * Press the back key to return to the previous page
  */
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
  if ((keyCode == KeyEvent.KEYCODE_BACK) &amp;&amp; ()) {
    ();
    return true;
  }
  return (keyCode, event);
}

There is another new method starting from Android 2.0. For Activity, you can get the Back key press event separately and directly rewrite the onBackPressed method. The code is as follows

@Override
public void onBackPressed() {
 // This is the logical code processed here, this method is only applicable to SDK version 2.0 or higherreturn ;
}

If you want to load HTML in the project, you can use the following method (provided that HTML is placed in the assets directory)

("file:///android_asset/");

If you want to load an HTML text directly, you can use the following method

("<html><body>abcdefg</body></html>", "text/html", "utf-8");

Here are some other usages of WebView:

Settings allow access to file data

().setAllowFileAccess(true);

Setting support for zoom

().setBuiltInZoomControls(true);

Set whether to save the password

().setSavePassword(false);

Settings support various devices

Copy the codeThe code is as follows:
().setUserAgentString("Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X;en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334bSafari/531.21.10");

Some methods to execute when loading a webview page

(new WebViewClient() {
    // Use your own defined webview to display when opening a new page, and do not use the system's own browser to display it    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
      (url);
      return true;
    }
    // What to do when starting to load a web page    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
      (view, url, favicon);
    }
    // Work to be done when the load is completed    @Override
    public void onPageFinished(WebView view, String url) {
      (view, url);
    }
    // What to do when loading errors    @Override
    public void onReceivedError(WebView view, int errorCode,
        String description, String failingUrl) {
      (view, errorCode, description, failingUrl);
    }
});

Process some dialog information in the web page (prompt dialog, dialog with selection, dialog with input)

(new WebChromeClient() {
    // Prompt dialog box    @Override
    public boolean onJsAlert(WebView view, String url, String message,
        final JsResult result) {
      // Build a Builder to display the alert dialog box in the web page      Builder builder = new Builder();
      ("Prompt Dialog");
      (message);
      (,
          new () {
            @Override
            public void onClick(DialogInterface dialog,
                int which) {
              ();
            }
          });
      (false);
      ();
      ();
      return true;
    }
    // Dialog box with buttons    @Override
    public boolean onJsConfirm(WebView view, String url,
        String message, final JsResult result) {
      Builder builder = new Builder();
      ("Dialogue with selection");
      (message);
      (,
          new () {
            @Override
            public void onClick(DialogInterface dialog,
                int which) {
              ();
            }
          });
      (,
          new () {
            @Override
            public void onClick(DialogInterface dialog,
                int which) {
              ();
            }
          });
      (false);
      ();
      ();
      return true;
    }
    // Dialog box with input box    @Override
    public boolean onJsPrompt(WebView view, String url, String message,
        String defaultValue, final JsPromptResult result) {
      LayoutInflater inflater = LayoutInflater
          .from();
      final View v = (, null);
      // Set the prompt information in the corresponding web page of TextView      ((TextView) ()).setText(message);
      // Set the input box in the corresponding web page of EditText      ((EditText) ())
          .setText(defaultValue);
      Builder builder = new Builder();
      ("Dialogue with input");
      (v);
      (,
          new () {
            @Override
            public void onClick(DialogInterface dialog,
                int which) {
              String value = ((EditText) v
                  .findViewById()).getText()
                  .toString();
              (value);
            }
          });
      (,
          new () {
            @Override
            public void onClick(DialogInterface dialog,
                int which) {
              ();
            }
          });
      (new () {
        @Override
        public void onCancel(DialogInterface dialog) {
          ();
        }
      });
      ();
      ();
      return true;
    }
    // Set the progress bar for web page loading    @Override
    public void onProgressChanged(WebView view, int newProgress) {
      ().setFeatureInt(
          Window.FEATURE_PROGRESS, newProgress * 100);
      (view, newProgress);
    }
    // Set the title of the application    @Override
    public void onReceivedTitle(WebView view, String title) {
      (title);
      (view, title);
    }
});

For more information about Android related content, please check out the topic of this site:Android development introduction and advanced tutorial》、《Android multimedia operation skills summary (audio, video, recording, etc.)》、《Summary of the usage of basic Android components》、《Android View View Tips Summary》、《Android layout layout tips summary"and"Android control usage summary

I hope this article will be helpful to everyone's Android programming design.