SoFunction
Updated on 2025-03-04

Detailed usage methods and common operations of WebView in Android development

Preface

In Android,WebViewis a powerful component for displaying web content in the application. It is capable of loading and displaying HTML content, and supports JavaScript and other browser features. The following are detailed usage methods and common operations:

1. Basic initialization and configuration

First, in the layout file (.xml) DefinitionWebView

<WebView
    android:
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

In Java or Kotlin files, use the following code to initializeWebViewAnd load a URL:

WebView webView = findViewById();
("");

2. Enable JavaScript

WebViewJavaScript is disabled by default. If you need to load a page containing JavaScript, you need to enable it:

().setJavaScriptEnabled(true);

3. Process page navigation

  • Overlay page navigation: Implement custom page loading logic, which can be implementedWebViewClientAnd set toWebView

    (new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            (url);
            return true; // Return true to block this URL and does not open an external browser    }
    });
    
  • Return to the previous page: Intercept the return button event toWebViewReturn to the previous page instead of exiting the application:
    @Override
    public void onBackPressed() {
        if (()) {
            ();
        } else {
            ();
        }
    }
    

4. Interact with JavaScript

WebViewSupports JavaScript calls to native code. Define a class for JavaScript callback method:

public class WebAppInterface {
    Context mContext;

    WebAppInterface(Context c) {
        mContext = c;
    }

    @JavascriptInterface
    public void showToast(String toast) {
        (mContext, toast, Toast.LENGTH_SHORT).show();
    }
}

Then, add this interface toWebView

(new WebAppInterface(this), "Android");

In JavaScript, you can pass("Hello")Call this method.

5. Load local HTML content

In addition to loading the URL,WebViewYou can also load local HTML files:

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

Or directly load the HTML string:

String htmlData = "<html><body>Hello, WebView!</body></html>";
(htmlData, "text/html", "UTF-8");

6. Support file upload and download

  • File upload:forWebViewProvide file upload support, you can useWebChromeClientofonShowFileChoosermethod.

    (new WebChromeClient() {
        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback&lt;Uri[]&gt; filePathCallback, FileChooserParams fileChooserParams) {
            // Process file selection logic        return true;
        }
    });
    
  • File download: By settingDownloadListenerImplement download function:
    (new DownloadListener() {
        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimeType, long contentLength) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            ((url));
            startActivity(intent);
        }
    });
    

7. Progress bar and loading instructions

Can be usedWebChromeClientCallbacks to implement page loading progress:

(new WebChromeClient() {
    @Override
    public void onProgressChanged(WebView view, int newProgress) {
        // Update the progress bar, or display the loading progress    }
});

8. Handle web page errors

Can be coveredWebViewClientofonReceivedErrorMethod to catch page loading errors:

(new WebViewClient() {
    @Override
    public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
        // Show error page or prompt    }
});

9. Security settings

WebViewIt has high flexibility, but is also prone to safety problems, so it is recommended:

  • usesetJavaScriptEnabled(true)When ensuring that the page source is credible.
  • Make sure to usehttpsTo transmit sensitive information.
  • Not allowedWebViewLoad untrusted content or pages.

Summarize

WebViewis a very powerful tool for loading web content in the application. By usingWebViewClientWebChromeClientDownloadListenerand other configurations can achieve rich web interaction functions while ensuring the security and stability of the application.

If you have specific functional requirements, you can check it in the official Android documentation.WebView APIDetailed description.

This is the article about the detailed usage methods and common operations of WebView in Android development. For more information about Android development WebView usage, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!