java.lang.Object
   ↳ android.view.View
     ↳ android.view.ViewGroup
       ↳ android.widget.AbsoluteLayout
         ↳ android.webkit.WebView

Class Overview

A View that displays web pages. This class is the basis upon which you can roll your own web browser or simply display some online content within your Activity. It uses the WebKit rendering engine to display web pages and includes methods to navigate forward and backward through a history, zoom in and out, perform text searches and more.

To enable the built-in zoom, set WebSettings.setBuiltInZoomControls(boolean) (introduced in API version 3).

Note that, in order for your Activity to access the Internet and load web pages in a WebView, you must add the INTERNET permissions to your Android Manifest file:

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

This must be a child of the element.

See the Web View tutorial.

Basic usage

By default, a WebView provides no browser-like widgets, does not enable JavaScript and web page errors are ignored. If your goal is only to display some HTML as a part of your UI, this is probably fine; the user won't need to interact with the web page beyond reading it, and the web page won't need to interact with the user. If you actually want a full-blown web browser, then you probably want to invoke the Browser application with a URL Intent rather than show it with a WebView. For example:

 Uri uri = Uri.parse("http://www.example.com");
 Intent intent = new Intent(Intent.ACTION_VIEW, uri);
 startActivity(intent);
 

See Intent for more information.

To provide a WebView in your own Activity, include a in your layout, or set the entire Activity window as a WebView during onCreate():

 WebView webview = new WebView(this);
 setContentView(webview);
 

Then load the desired web page:

 // Simplest usage: note that an exception will NOT be thrown
 // if there is an error loading this page (see below).
 webview.loadUrl("http://slashdot.org/");

 // OR, you can also load from an HTML string:
 String summary = "<html><body>You scored <b>192</b> points.</body></html>";
 webview.loadData(summary, "text/html", null);
 // ... although note that there are restrictions on what this HTML can do.
 // See the JavaDocs for loadData() and loadDataWithBaseURL() for more info.
 

A WebView has several customization points where you can add your own behavior. These are:

  • Creating and setting a WebChromeClient subclass. This class is called when something that might impact a browser UI happens, for instance, progress updates and JavaScript alerts are sent here (see Debugging Tasks).
  • Creating and setting a WebViewClient subclass. It will be called when things happen that impact the rendering of the content, eg, errors or form submissions. You can also intercept URL loading here (via shouldOverrideUrlLoading()).
  • Modifying the WebSettings, such as enabling JavaScript with setJavaScriptEnabled().
  • Adding JavaScript-to-Java interfaces with the addJavascriptInterface(Object, String) method. This lets you bind Java objects into the WebView so they can be controlled from the web pages JavaScript.

Here's a more complicated example, showing error handling, settings, and progress notification:

 // Let's display the progress in the activity title bar, like the
 // browser app does.
 getWindow().requestFeature(Window.FEATURE_PROGRESS);

 webview.getSettings().setJavaScriptEnabled(true);

 final Activity activity = this;
 webview.setWebChromeClient(new WebChromeClient() {
   public void onProgressChanged(WebView view, int progress) {
     // Activities and WebViews measure progress with different scales.
     // The progress meter will automatically disappear when we reach 100%
     activity.setProgress(progress * 1000);
   }
 });
 webview.setWebViewClient(new WebViewClient() {
   public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
     Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
   }
 });

 webview.loadUrl("http://slashdot.org/");
 

Cookie and window management

For obvious security reasons, your application has its own cache, cookie store etc.—it does not share the Browser application's data. Cookies are managed on a separate thread, so operations like index building don't block the UI thread. Follow the instructions in CookieSyncManager if you want to use cookies in your application.

By default, requests by the HTML to open new windows are ignored. This is true whether they be opened by JavaScript or by the target attribute on a link. You can customize your WebChromeClient to provide your own behaviour for opening multiple windows, and render them in whatever manner you want.

The standard behavior for an Activity is to be destroyed and recreated when the device orientation or any other configuration changes. This will cause the WebView to reload the current page. If you don't want that, you can set your Activity to handle the orientation and keyboardHidden changes, and then just leave the WebView alone. It'll automatically re-orient itself as appropriate. Read Handling Runtime Changes for more information about how to handle configuration changes during runtime.

Building web pages to support different screen densities

The screen density of a device is based on the screen resolution. A screen with low density has fewer available pixels per inch, where a screen with high density has more — sometimes significantly more — pixels per inch. The density of a screen is important because, other things being equal, a UI element (such as a button) whose height and width are defined in terms of screen pixels will appear larger on the lower density screen and smaller on the higher density screen. For simplicity, Android collapses all actual screen densities into three generalized densities: high, medium, and low.

By default, WebView scales a web page so that it is drawn at a size that matches the default appearance on a medium density screen. So, it applies 1.5x scaling on a high density screen (because its pixels are smaller) and 0.75x scaling on a low density screen (because its pixels are bigger). Starting with API Level 5 (Android 2.0), WebView supports DOM, CSS, and meta tag features to help you (as a web developer) target screens with different screen densities.

Here's a summary of the features you can use to handle different screen densities:

  • The window.devicePixelRatio DOM property. The value of this property specifies the default scaling factor used for the current device. For example, if the value of window.devicePixelRatio is "1.0", then the device is considered a medium density (mdpi) device and default scaling is not applied to the web page; if the value is "1.5", then the device is considered a high density device (hdpi) and the page content is scaled 1.5x; if the value is "0.75", then the device is considered a low density device (ldpi) and the content is scaled 0.75x. However, if you specify the "target-densitydpi" meta property (discussed below), then you can stop this default scaling behavior.
  • The -webkit-device-pixel-ratio CSS media query. Use this to specify the screen densities for which this style sheet is to be used. The corresponding value should be either "0.75", "1", or "1.5", to indicate that the styles are for devices with low density, medium density, or high density screens, respectively. For example:
     <link rel="stylesheet" media="screen and (-webkit-device-pixel-ratio:1.5)" href="hdpi.css" />

    The hdpi.css stylesheet is only used for devices with a screen pixel ration of 1.5, which is the high density pixel ratio.

  • The target-densitydpi property for the viewport meta tag. You can use this to specify the target density for which the web page is designed, using the following values:
    • device-dpi - Use the device's native dpi as the target dpi. Default scaling never occurs.
    • high-dpi - Use hdpi as the target dpi. Medium and low density screens scale down as appropriate.
    • medium-dpi - Use mdpi as the target dpi. High density screens scale up and low density screens scale down. This is also the default behavior.
    • low-dpi - Use ldpi as the target dpi. Medium and high density screens scale up as appropriate.
    • - Specify a dpi value to use as the target dpi (accepted values are 70-400).

    Here's an example meta tag to specify the target density:

    <meta name="viewport" content="target-densitydpi=device-dpi" />

If you want to modify your web page for different densities, by using the -webkit-device-pixel-ratio CSS media query and/or the window.devicePixelRatio DOM property, then you should set the target-densitydpi meta property to device-dpi. This stops Android from performing scaling in your web page and allows you to make the necessary adjustments for each density via CSS and JavaScript.

Summary

Nested Classes
class WebView.HitTestResult  
interface WebView.PictureListener This interface is deprecated. This interface is now obsolete.  
class WebView.WebViewTransport Transportation object for returning WebView across thread boundaries. 
[Expand]
Inherited XML Attributes
From class android.view.ViewGroup
From class android.view.View
Constants
String SCHEME_GEO URI scheme for map address
String SCHEME_MAILTO URI scheme for email address
String SCHEME_TEL URI scheme for telephone number
[Expand]
Inherited Constants
From class android.view.ViewGroup
From class android.view.View
[Expand]
Inherited Fields
From class android.view.View
Public Constructors
WebView(Context context)
Construct a new WebView with a Context object.
WebView(Context context, AttributeSet attrs)
Construct a new WebView with layout parameters.
WebView(Context context, AttributeSet attrs, int defStyle)
Construct a new WebView with layout parameters and a default style.
WebView(Context context, AttributeSet attrs, int defStyle, boolean privateBrowsing)
Construct a new WebView with layout parameters and a default style.
Public Methods
void addJavascriptInterface(Object obj, String interfaceName)
Use this function to bind an object to JavaScript so that the methods can be accessed from JavaScript.
boolean canGoBack()
Return true if this WebView has a back history item.
boolean canGoBackOrForward(int steps)
Return true if the page can go back or forward the given number of steps.
boolean canGoForward()
Return true if this WebView has a forward history item.
boolean canZoomIn()
boolean canZoomOut()
Picture capturePicture()
Return a new picture that captures the current display of the webview.
void clearCache(boolean includeDiskFiles)
Clear the resource cache.
void clearFormData()
Make sure that clearing the form data removes the adapter from the currently focused textfield if there is one.
void clearHistory()
Tell the WebView to clear its internal back/forward list.
void clearMatches()
void clearSslPreferences()
Clear the SSL preferences table stored in response to proceeding with SSL certificate errors.
void clearView()
Clear the view so that onDraw() will draw nothing but white background, and onMeasure() will return 0 if MeasureSpec is not MeasureSpec.EXACTLY
void computeScroll()
Called by a parent to request that a child update its values for mScrollX and mScrollY if necessary.
WebBackForwardList copyBackForwardList()
Return the WebBackForwardList for this WebView.
void debugDump()
This method is deprecated. This method is now obsolete.
void destroy()
Destroy the internal state of the WebView.
static void disablePlatformNotifications()
This method is deprecated. This method is now obsolete.
boolean dispatchKeyEvent(KeyEvent event)
Dispatch a key event to the next view on the focus path.
void documentHasImages(Message response)
Query the document to see if it contains any image references.
void emulateShiftHeld()
This method is deprecated. This method is now obsolete.
static void enablePlatformNotifications()
This method is deprecated. This method is now obsolete.
static String findAddress(String addr)
Return the first substring consisting of the address of a physical location.
int findAll(String find)
void findNext(boolean forward)
void flingScroll(int vx, int vy)
void freeMemory()
Call this to inform the view that memory is low so that it can free any available memory.
SslCertificate getCertificate()
int getContentHeight()
Bitmap getFavicon()
Get the favicon for the current page.
WebView.HitTestResult getHitTestResult()
Return a HitTestResult based on the current cursor node.
String[] getHttpAuthUsernamePassword(String host, String realm)
Retrieve the HTTP authentication username and password for a given host & realm pair
String getOriginalUrl()
Get the original url for the current page.
int getProgress()
Get the progress for the current page.
float getScale()
Return the current scale of the WebView
WebSettings getSettings()
Return the WebSettings object used to control the settings for this WebView.
String getTitle()
Get the title for the current page.
String getUrl()
Get the url for the current page.
int getVisibleTitleHeight()
This method is deprecated. This method is now obsolete.
View getZoomControls()
This method is deprecated. The built-in zoom mechanism is preferred, see setBuiltInZoomControls(boolean).
void goBack()
Go back in the history of this WebView.
void goBackOrForward(int steps)
Go to the history item that is the number of steps away from the current item.
void goForward()
Go forward in the history of this WebView.
void invokeZoomPicker()
Invoke the graphical zoom picker widget for this WebView.
boolean isPrivateBrowsingEnabled()
Returns true if private browsing is enabled in this WebView.
void loadData(String data, String mimeType, String encoding)
Load the given data into the WebView using a 'data' scheme URL.
void loadDataWithBaseURL(String baseUrl, String data, String mimeType, String encoding, String historyUrl)
Load the given data into the WebView, using baseUrl as the base URL for the content.
void loadUrl(String url)
Load the given URL.
void loadUrl(String url, Map<StringString> additionalHttpHeaders)
Load the given URL with the specified additional HTTP headers.
void onChildViewAdded(View parent, View child)
This method is deprecated. WebView no longer needs to implement ViewGroup.OnHierarchyChangeListener. This method does nothing now.
void onChildViewRemoved(View p, View child)
This method is deprecated. WebView no longer needs to implement ViewGroup.OnHierarchyChangeListener. This method does nothing now.
InputConnection onCreateInputConnection(EditorInfo outAttrs)
Create a new InputConnection for an InputMethod to interact with the view.
boolean onGenericMotionEvent(MotionEvent event)
Implement this method to handle generic motion events.
void onGlobalFocusChanged(View oldFocus, View newFocus)
This method is deprecated. WebView should not have implemented ViewTreeObserver.OnGlobalFocusChangeListener. This method does nothing now.
boolean onHoverEvent(MotionEvent event)
Implement this method to handle hover events.
void onInitializeAccessibilityEvent(AccessibilityEvent event)
Initializes an AccessibilityEvent with information about this View which is the event source.
void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info)
Initializes an AccessibilityNodeInfo with information about this view.
boolean onKeyDown(int keyCode, KeyEvent event)
Default implementation of KeyEvent.Callback.onKeyDown(): perform press of the view when KEYCODE_DPAD_CENTER or KEYCODE_ENTER is released, if the view is enabled and clickable.
boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event)
Default implementation of KeyEvent.Callback.onKeyMultiple(): always returns false (doesn't handle the event).
boolean onKeyUp(int keyCode, KeyEvent event)
Default implementation of KeyEvent.Callback.onKeyUp(): perform clicking of the view when KEYCODE_DPAD_CENTER or KEYCODE_ENTER is released.
void onPause()
Call this to pause any extra processing associated with this WebView and its associated DOM, plugins, JavaScript etc.
void onResume()
Call this to resume a WebView after a previous call to onPause().
boolean onTouchEvent(MotionEvent ev)
Implement this method to handle touch screen motion events.
boolean onTrackballEvent(MotionEvent ev)
Implement this method to handle trackball motion events.
void onWindowFocusChanged(boolean hasWindowFocus)
Called when the window containing this view gains or loses focus.
boolean overlayHorizontalScrollbar()
Return whether horizontal scrollbar has overlay style
boolean overlayVerticalScrollbar()
Return whether vertical scrollbar has overlay style
boolean pageDown(boolean bottom)
Scroll the contents of the view down by half the page size
boolean pageUp(boolean top)
Scroll the contents of the view up by half the view size
void pauseTimers()
Pause all layout, parsing, and JavaScript timers for all webviews.
boolean performLongClick()
Call this view's OnLongClickListener, if it is defined.
void postUrl(String url, byte[] postData)
Load the url with postData using "POST" method into the WebView.
void reload()
Reload the current url.
void removeJavascriptInterface(String interfaceName)
Removes a previously added JavaScript interface with the given name.
boolean requestChildRectangleOnScreen(View child, Rect rect, boolean immediate)
Called when a child of this group wants a particular rectangle to be positioned onto the screen.
boolean requestFocus(int direction, Rect previouslyFocusedRect)
Call this to try to give focus to a specific view or to one of its descendants and give it hints about the direction and a specific rectangle that the focus is coming from. Looks for a view to give focus to respecting the setting specified by getDescendantFocusability().
void requestFocusNodeHref(Message hrefMsg)
Request the anchor or image element URL at the last tapped point.
void requestImageRef(Message msg)
Request the url of the image last touched by the user.
boolean restorePicture(Bundle b, File src)
This method is deprecated. This method is now obsolete.
WebBackForwardList restoreState(Bundle inState)
Restore the state of this WebView from the given map used in onRestoreInstanceState(Bundle).
void resumeTimers()
Resume all layout, parsing, and JavaScript timers for all webviews.
void savePassword(String host, String username, String password)
Save the username and password for a particular host in the WebView's internal database.
boolean savePicture(Bundle b, File dest)
This method is deprecated. This method is now obsolete.
WebBackForwardList saveState(Bundle outState)
Save the state of this WebView used in onSaveInstanceState(Bundle).
void saveWebArchive(String filename)
Saves the current view as a web archive.
void saveWebArchive(String basename, boolean autoname, ValueCallback<String> callback)
Saves the current view as a web archive.
void setBackgroundColor(int color)
Set the background color.
void setCertificate(SslCertificate certificate)
Sets the SSL certificate for the main top-level page.
void setDownloadListener(DownloadListener listener)
Register the interface to be used when content can not be handled by the rendering engine, and should be downloaded instead.
void setHorizontalScrollbarOverlay(boolean overlay)
Specify whether the horizontal scrollbar has overlay style.
void setHttpAuthUsernamePassword(String host, String realm, String username, String password)
Set the HTTP authentication credentials for a given host and realm.
void setInitialScale(int scaleInPercent)
Set the initial scale for the WebView.
void setLayoutParams(ViewGroup.LayoutParams params)
Set the layout parameters associated with this view.
void setMapTrackballToArrowKeys(boolean setMap)
void setNetworkAvailable(boolean networkUp)
Inform WebView of the network state.
void setOverScrollMode(int mode)
Set the over-scroll mode for this view.
void setPictureListener(WebView.PictureListener listener)
This method is deprecated. This method is now obsolete.
void setScrollBarStyle(int style)

Specify the style of the scrollbars.

void setVerticalScrollbarOverlay(boolean overlay)
Specify whether the vertical scrollbar has overlay style.
void setWebChromeClient(WebChromeClient client)
Set the chrome handler.
void setWebViewClient(WebViewClient client)
Set the WebViewClient that will receive various notifications and requests.
boolean shouldDelayChildPressedState()
Return true if the pressed state should be delayed for children or descendants of this ViewGroup.
boolean showFindDialog(String text, boolean showIme)
Start an ActionMode for finding text in this WebView.
void stopLoading()
Stop the current load.
boolean zoomIn()
Perform zoom in in the webview
boolean zoomOut()
Perform zoom out in the webview
Protected Methods
int computeHorizontalScrollOffset()

Compute the horizontal offset of the horizontal scrollbar's thumb within the horizontal range.

int computeHorizontalScrollRange()

Compute the horizontal range that the horizontal scrollbar represents.

int computeVerticalScrollExtent()

Compute the vertical extent of the horizontal scrollbar's thumb within the vertical range.

int computeVerticalScrollOffset()

Compute the vertical offset of the vertical scrollbar's thumb within the horizontal range.

int computeVerticalScrollRange()

Compute the vertical range that the vertical scrollbar represents.

boolean drawChild(Canvas canvas, View child, long drawingTime)
Draw one child of this View Group.
void finalize()
Invoked when the garbage collector has detected that this instance is no longer reachable.
void onAttachedToWindow()
This is called when the view is attached to a window.
void onConfigurationChanged(Configuration newConfig)
Called when the current configuration of the resources being used by the application have changed.
void onDetachedFromWindow()
This is called when the view is detached from a window.
void onDraw(Canvas canvas)
Implement this to do your drawing.
void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect)
Called by the view system when the focus state of this view changes.
void onMeasure(int widthMeasureSpec, int heightMeasureSpec)

Measure the view and its content to determine the measured width and the measured height.

void onOverScrolled(int scrollX, int scrollY, boolean clampedX, boolean clampedY)
Called by overScrollBy(int, int, int, int, int, int, int, int, boolean) to respond to the results of an over-scroll operation.
void onScrollChanged(int l, int t, int oldl, int oldt)
This is called in response to an internal scroll in this view (i.e., the view scrolled its own contents).
void onSizeChanged(int w, int h, int ow, int oh)
This is called during layout when the size of this view has changed.
void onVisibilityChanged(View changedView, int visibility)
Called when the visibility of the view or an ancestor of the view is changed.
void onWindowVisibilityChanged(int visibility)
Called when the window containing has change its visibility (between GONE, INVISIBLE, and VISIBLE).
[Expand]
Inherited Methods
From class android.widget.AbsoluteLayout
From class android.view.ViewGroup
From class android.view.View
From class java.lang.Object
From interface android.graphics.drawable.Drawable.Callback