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> extraHeaders)
Load the given url with the extra 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.
[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
From interface android.view.KeyEvent.Callback
From interface android.view.ViewGroup.OnHierarchyChangeListener
From interface android.view.ViewManager
From interface android.view.ViewParent
From interface android.view.ViewTreeObserver.OnGlobalFocusChangeListener
From interface android.view.accessibility.AccessibilityEventSource

Constants

public static final String SCHEME_GEO

Since: API Level 1

URI scheme for map address

Constant Value: "geo:0,0?q="

public static final String SCHEME_MAILTO

Since: API Level 1

URI scheme for email address

Constant Value: "mailto:"

public static final String SCHEME_TEL

Since: API Level 1

URI scheme for telephone number

Constant Value: "tel:"

Public Constructors

public WebView (Context context)

Since: API Level 1

Construct a new WebView with a Context object.

Parameters
context A Context object used to access application assets.

public WebView (Context context, AttributeSet attrs)

Since: API Level 1

Construct a new WebView with layout parameters.

Parameters
context A Context object used to access application assets.
attrs An AttributeSet passed to our parent.

public WebView (Context context, AttributeSet attrs, int defStyle)

Since: API Level 1

Construct a new WebView with layout parameters and a default style.

Parameters
context A Context object used to access application assets.
attrs An AttributeSet passed to our parent.
defStyle The default style resource ID.

public WebView (Context context, AttributeSet attrs, int defStyle, boolean privateBrowsing)

Since: API Level 11

Construct a new WebView with layout parameters and a default style.

Parameters
context A Context object used to access application assets.
attrs An AttributeSet passed to our parent.
defStyle The default style resource ID.

Public Methods

public void addJavascriptInterface (Object obj, String interfaceName)

Since: API Level 1

Use this function to bind an object to JavaScript so that the methods can be accessed from JavaScript.

IMPORTANT:

  • Using addJavascriptInterface() allows JavaScript to control your application. This can be a very useful feature or a dangerous security issue. When the HTML in the WebView is untrustworthy (for example, part or all of the HTML is provided by some person or process), then an attacker could inject HTML that will execute your code and possibly any code of the attacker's choosing.
    Do not use addJavascriptInterface() unless all of the HTML in this WebView was written by you.
  • The Java object that is bound runs in another thread and not in the thread that it was constructed in.

Parameters
obj The class instance to bind to JavaScript, null instances are ignored.
interfaceName The name to used to expose the instance in JavaScript.

public boolean canGoBack ()

Since: API Level 1

Return true if this WebView has a back history item.

Returns
  • True iff this WebView has a back history item.

public boolean canGoBackOrForward (int steps)

Since: API Level 1

Return true if the page can go back or forward the given number of steps.

Parameters
steps The negative or positive number of steps to move the history.

public boolean canGoForward ()

Since: API Level 1

Return true if this WebView has a forward history item.

Returns
  • True iff this Webview has a forward history item.

public boolean canZoomIn ()

Since: API Level 11

Returns
  • TRUE if the WebView can be zoomed in.

public boolean canZoomOut ()

Since: API Level 11

Returns
  • TRUE if the WebView can be zoomed out.

public Picture capturePicture ()

Since: API Level 1

Return a new picture that captures the current display of the webview. This is a copy of the display, and will be unaffected if the webview later loads a different URL.

Returns
  • a picture containing the current contents of the view. Note this picture is of the entire document, and is not restricted to the bounds of the view.

public void clearCache (boolean includeDiskFiles)

Since: API Level 1

Clear the resource cache. Note that the cache is per-application, so this will clear the cache for all WebViews used.

Parameters
includeDiskFiles If false, only the RAM cache is cleared.

public void clearFormData ()

Since: API Level 1

Make sure that clearing the form data removes the adapter from the currently focused textfield if there is one.

public void clearHistory ()

Since: API Level 1

Tell the WebView to clear its internal back/forward list.

public void clearMatches ()

Since: API Level 3

public void clearSslPreferences ()

Since: API Level 1

Clear the SSL preferences table stored in response to proceeding with SSL certificate errors.

public void clearView ()

Since: API Level 1

Clear the view so that onDraw() will draw nothing but white background, and onMeasure() will return 0 if MeasureSpec is not MeasureSpec.EXACTLY

public void computeScroll ()

Since: API Level 1

Called by a parent to request that a child update its values for mScrollX and mScrollY if necessary. This will typically be done if the child is animating a scroll using a Scroller object.

public WebBackForwardList copyBackForwardList ()

Since: API Level 1

Return the WebBackForwardList for this WebView. This contains the back/forward list for use in querying each item in the history stack. This is a copy of the private WebBackForwardList so it contains only a snapshot of the current state. Multiple calls to this method may return different objects. The object returned from this method will not be updated to reflect any new state.

public void debugDump ()

Since: API Level 1

This method is deprecated.
This method is now obsolete.

public void destroy ()

Since: API Level 1

Destroy the internal state of the WebView. This method should be called after the WebView has been removed from the view system. No other methods may be called on a WebView after destroy.

public static void disablePlatformNotifications ()

Since: API Level 1

This method is deprecated.
This method is now obsolete.

Disables platform notifications of data state and proxy changes. Notifications are enabled by default.

public boolean dispatchKeyEvent (KeyEvent event)

Since: API Level 1

Dispatch a key event to the next view on the focus path. This path runs from the top of the view tree down to the currently focused view. If this view has focus, it will dispatch to itself. Otherwise it will dispatch the next node down the focus path. This method also fires any key listeners.

Parameters
event The key event to be dispatched.
Returns
  • True if the event was handled, false otherwise.

public void documentHasImages (Message response)

Since: API Level 1

Query the document to see if it contains any image references. The message object will be dispatched with arg1 being set to 1 if images were found and 0 if the document does not reference any images.

Parameters
response The message that will be dispatched with the result.

public void emulateShiftHeld ()

Since: API Level 8

This method is deprecated.
This method is now obsolete.

Use this method to put the WebView into text selection mode. Do not rely on this functionality; it will be deprecated in the future.

public static void enablePlatformNotifications ()

Since: API Level 1

This method is deprecated.
This method is now obsolete.

Enables platform notifications of data state and proxy changes. Notifications are enabled by default.

public static String findAddress (String addr)

Since: API Level 1

Return the first substring consisting of the address of a physical location. Currently, only addresses in the United States are detected, and consist of: - a house number - a street name - a street type (Road, Circle, etc), either spelled out or abbreviated - a city name - a state or territory, either spelled out or two-letter abbr. - an optional 5 digit or 9 digit zip code. All names must be correctly capitalized, and the zip code, if present, must be valid for the state. The street type must be a standard USPS spelling or abbreviation. The state or territory must also be spelled or abbreviated using USPS standards. The house number may not exceed five digits.

Parameters
addr The string to search for addresses.
Returns
  • the address, or if no address is found, return null.

public int findAll (String find)

Since: API Level 3

public void findNext (boolean forward)

Since: API Level 3

public void flingScroll (int vx, int vy)

Since: API Level 1

public void freeMemory ()

Since: API Level 7

Call this to inform the view that memory is low so that it can free any available memory.

public SslCertificate getCertificate ()

Since: API Level 1

Returns
  • The SSL certificate for the main top-level page or null if there is no certificate (the site is not secure).

public int getContentHeight ()

Since: API Level 1

Returns
  • the height of the HTML content.

public Bitmap getFavicon ()

Since: API Level 1

Get the favicon for the current page. This is the favicon of the current page until WebViewClient.onReceivedIcon is called.

Returns
  • The favicon for the current page.

public WebView.HitTestResult getHitTestResult ()

Since: API Level 1

Return a HitTestResult based on the current cursor node. If a HTML::a tag is found and the anchor has a non-JavaScript url, the HitTestResult type is set to SRC_ANCHOR_TYPE and the url is set in the "extra" field. If the anchor does not have a url or if it is a JavaScript url, the type will be UNKNOWN_TYPE and the url has to be retrieved through requestFocusNodeHref(Message) asynchronously. If a HTML::img tag is found, the HitTestResult type is set to IMAGE_TYPE and the url is set in the "extra" field. A type of SRC_IMAGE_ANCHOR_TYPE indicates an anchor with a url that has an image as a child node. If a phone number is found, the HitTestResult type is set to PHONE_TYPE and the phone number is set in the "extra" field of HitTestResult. If a map address is found, the HitTestResult type is set to GEO_TYPE and the address is set in the "extra" field of HitTestResult. If an email address is found, the HitTestResult type is set to EMAIL_TYPE and the email is set in the "extra" field of HitTestResult. Otherwise, HitTestResult type is set to UNKNOWN_TYPE.

public String[] getHttpAuthUsernamePassword (String host, String realm)

Since: API Level 1

Retrieve the HTTP authentication username and password for a given host & realm pair

Parameters
host The host for which the credentials apply.
realm The realm for which the credentials apply.
Returns
  • String[] if found, String[0] is username, which can be null and String[1] is password. Return null if it can't find anything.

public String getOriginalUrl ()

Since: API Level 3

Get the original url for the current page. This is not always the same as the url passed to WebViewClient.onPageStarted because although the load for that url has begun, the current page may not have changed. Also, there may have been redirects resulting in a different url to that originally requested.

Returns
  • The url that was originally requested for the current page.

public int getProgress ()

Since: API Level 1

Get the progress for the current page.

Returns
  • The progress for the current page between 0 and 100.

public float getScale ()

Since: API Level 1

Return the current scale of the WebView

Returns
  • The current scale.

public WebSettings getSettings ()

Since: API Level 1

Return the WebSettings object used to control the settings for this WebView.

Returns
  • A WebSettings object that can be used to control this WebView's settings.

public String getTitle ()

Since: API Level 1

Get the title for the current page. This is the title of the current page until WebViewClient.onReceivedTitle is called.

Returns
  • The title for the current page.

public String getUrl ()

Since: API Level 1

Get the url for the current page. This is not always the same as the url passed to WebViewClient.onPageStarted because although the load for that url has begun, the current page may not have changed.

Returns
  • The url for the current page.

public int getVisibleTitleHeight ()

Since: API Level 11

This method is deprecated.
This method is now obsolete.

Return the amount of the titlebarview (if any) that is visible

public View getZoomControls ()

Since: API Level 1

This method is deprecated.
The built-in zoom mechanism is preferred, see setBuiltInZoomControls(boolean).

Returns a view containing zoom controls i.e. +/- buttons. The caller is in charge of installing this view to the view hierarchy. This view will become visible when the user starts scrolling via touch and fade away if the user does not interact with it.

API version 3 introduces a built-in zoom mechanism that is shown automatically by the MapView. This is the preferred approach for showing the zoom UI.

public void goBack ()

Since: API Level 1

Go back in the history of this WebView.

public void goBackOrForward (int steps)

Since: API Level 1

Go to the history item that is the number of steps away from the current item. Steps is negative if backward and positive if forward.

Parameters
steps The number of steps to take back or forward in the back forward list.

public void goForward ()

Since: API Level 1

Go forward in the history of this WebView.

public void invokeZoomPicker ()

Since: API Level 1

Invoke the graphical zoom picker widget for this WebView. This will result in the zoom widget appearing on the screen to control the zoom level of this WebView.

public boolean isPrivateBrowsingEnabled ()

Since: API Level 11

Returns true if private browsing is enabled in this WebView.

public void loadData (String data, String mimeType, String encoding)

Since: API Level 1

Load the given data into the WebView using a 'data' scheme URL.

Note that JavaScript's same origin policy means that script running in a page loaded using this method will be unable to access content loaded using any scheme other than 'data', including 'http(s)'. To avoid this restriction, use loadDataWithBaseURL() with an appropriate base URL.

If the value of the encoding parameter is 'base64', then the data must be encoded as base64. Otherwise, the data must use ASCII encoding for octets inside the range of safe URL characters and use the standard %xx hex encoding of URLs for octets outside that range. For example, '#', '%', '\', '?' should be replaced by %23, %25, %27, %3f respectively.

The 'data' scheme URL formed by this method uses the default US-ASCII charset. If you need need to set a different charset, you should form a 'data' scheme URL which explicitly specifies a charset parameter in the mediatype portion of the URL and call loadUrl(String) instead. Note that the charset obtained from the mediatype portion of a data URL always overrides that specified in the HTML or XML document itself.

Parameters
data A String of data in the given encoding.
mimeType The MIME type of the data, e.g. 'text/html'.
encoding The encoding of the data.

public void loadDataWithBaseURL (String baseUrl, String data, String mimeType, String encoding, String historyUrl)

Since: API Level 1

Load the given data into the WebView, using baseUrl as the base URL for the content. The base URL is used both to resolve relative URLs and when applying JavaScript's same origin policy. The historyUrl is used for the history entry.

Note that content specified in this way can access local device files (via 'file' scheme URLs) only if baseUrl specifies a scheme other than 'http', 'https', 'ftp', 'ftps', 'about' or 'javascript'.

If the base URL uses the data scheme, this method is equivalent to calling loadData() and the historyUrl is ignored.

Parameters
baseUrl URL to use as the page's base URL. If null defaults to 'about:blank'
data A String of data in the given encoding.
mimeType The MIMEType of the data, e.g. 'text/html'. If null, defaults to 'text/html'.
encoding The encoding of the data.
historyUrl URL to use as the history entry, if null defaults to 'about:blank'.

public void loadUrl (String url)

Since: API Level 1

Load the given url.

Parameters
url The url of the resource to load.

public void loadUrl (String url, Map<StringString> extraHeaders)

Since: API Level 8

Load the given url with the extra headers.

Parameters
url The url of the resource to load.
extraHeaders The extra headers sent with this url. This should not include the common headers like "user-agent". If it does, it will be replaced by the intrinsic value of the WebView.

public void onChildViewAdded (View parent, View child)

Since: API Level 1

This method is deprecated.
WebView no longer needs to implement ViewGroup.OnHierarchyChangeListener. This method does nothing now.

Called when a new child is added to a parent view.

Parameters
parent the view in which a child was added
child the new child view added in the hierarchy

public void onChildViewRemoved (View p, View child)

Since: API Level 1

This method is deprecated.
WebView no longer needs to implement ViewGroup.OnHierarchyChangeListener. This method does nothing now.

Called when a child is removed from a parent view.

Parameters
p the view from which the child was removed
child the child removed from the hierarchy

public InputConnection onCreateInputConnection (EditorInfo outAttrs)

Since: API Level 3

Create a new InputConnection for an InputMethod to interact with the view. The default implementation returns null, since it doesn't support input methods. You can override this to implement such support. This is only needed for views that take focus and text input.

When implementing this, you probably also want to implement onCheckIsTextEditor() to indicate you will return a non-null InputConnection.

Parameters
outAttrs Fill in with attribute information about the connection.

public boolean onGenericMotionEvent (MotionEvent event)

Since: API Level 12

Implement this method to handle generic motion events.

Generic motion events describe joystick movements, mouse hovers, track pad touches, scroll wheel movements and other input events. The source of the motion event specifies the class of input that was received. Implementations of this method must examine the bits in the source before processing the event. The following code example shows how this is done.

Generic motion events with source class SOURCE_CLASS_POINTER are delivered to the view under the pointer. All other generic motion events are delivered to the focused view.

 public boolean onGenericMotionEvent(MotionEvent event) {
     if ((event.getSource() & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
         if (event.getAction() == MotionEvent.ACTION_MOVE) {
             // process the joystick movement...
             return true;
         }
     }
     if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
         switch (event.getAction()) {
             case MotionEvent.ACTION_HOVER_MOVE:
                 // process the mouse hover movement...
                 return true;
             case MotionEvent.ACTION_SCROLL:
                 // process the scroll wheel movement...
                 return true;
         }
     }
     return super.onGenericMotionEvent(event);
 }

Parameters
event The generic motion event being processed.
Returns
  • True if the event was handled, false otherwise.

public void onGlobalFocusChanged (View oldFocus, View newFocus)

Since: API Level 1

This method is deprecated.
WebView should not have implemented ViewTreeObserver.OnGlobalFocusChangeListener. This method does nothing now.

Callback method to be invoked when the focus changes in the view tree. When the view tree transitions from touch mode to non-touch mode, oldFocus is null. When the view tree transitions from non-touch mode to touch mode, newFocus is null. When focus changes in non-touch mode (without transition from or to touch mode) either oldFocus or newFocus can be null.

Parameters
oldFocus The previously focused view, if any.
newFocus The newly focused View, if any.

public boolean onHoverEvent (MotionEvent event)

Since: API Level 14

Implement this method to handle hover events.

This method is called whenever a pointer is hovering into, over, or out of the bounds of a view and the view is not currently being touched. Hover events are represented as pointer events with action ACTION_HOVER_ENTER, ACTION_HOVER_MOVE, or ACTION_HOVER_EXIT.

  • The view receives a hover event with action ACTION_HOVER_ENTER when the pointer enters the bounds of the view.
  • The view receives a hover event with action ACTION_HOVER_MOVE when the pointer has already entered the bounds of the view and has moved.
  • The view receives a hover event with action ACTION_HOVER_EXIT when the pointer has exited the bounds of the view or when the pointer is about to go down due to a button click, tap, or similar user action that causes the view to be touched.

The view should implement this method to return true to indicate that it is handling the hover event, such as by changing its drawable state.

The default implementation calls setHovered(boolean) to update the hovered state of the view when a hover enter or hover exit event is received, if the view is enabled and is clickable. The default implementation also sends hover accessibility events.

Parameters
event The motion event that describes the hover.
Returns
  • True if the view handled the hover event.

public void onInitializeAccessibilityEvent (AccessibilityEvent event)

Since: API Level 14

Initializes an AccessibilityEvent with information about this View which is the event source. In other words, the source of an accessibility event is the view whose state change triggered firing the event.

Example: Setting the password property of an event in addition to properties set by the super implementation:

 public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
     super.onInitializeAccessibilityEvent(event);
     event.setPassword(true);
 }

If an View.AccessibilityDelegate has been specified via calling setAccessibilityDelegate(AccessibilityDelegate) its onInitializeAccessibilityEvent(View, AccessibilityEvent) is responsible for handling this call.

Note: Always call the super implementation before adding information to the event, in case the default implementation has basic information to add.

Parameters
event The event to initialize.

public void onInitializeAccessibilityNodeInfo (AccessibilityNodeInfo info)

Since: API Level 14

Initializes an AccessibilityNodeInfo with information about this view. The base implementation sets:

Subclasses should override this method, call the super implementation, and set additional attributes.

If an View.AccessibilityDelegate has been specified via calling setAccessibilityDelegate(AccessibilityDelegate) its onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo) is responsible for handling this call.

Parameters
info The instance to initialize.

public boolean onKeyDown (int keyCode, KeyEvent event)

Since: API Level 1

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.

Parameters
keyCode A key code that represents the button pressed, from KeyEvent.
event The KeyEvent object that defines the button action.
Returns
  • If you handled the event, return true. If you want to allow the event to be handled by the next receiver, return false.

public boolean onKeyMultiple (int keyCode, int repeatCount, KeyEvent event)

Since: API Level 1

Default implementation of KeyEvent.Callback.onKeyMultiple(): always returns false (doesn't handle the event).

Parameters
keyCode A key code that represents the button pressed, from KeyEvent.
repeatCount The number of times the action was made.
event The KeyEvent object that defines the button action.
Returns
  • If you handled the event, return true. If you want to allow the event to be handled by the next receiver, return false.

public boolean onKeyUp (int keyCode, KeyEvent event)

Since: API Level 1

Default implementation of KeyEvent.Callback.onKeyUp(): perform clicking of the view when KEYCODE_DPAD_CENTER or KEYCODE_ENTER is released.

Parameters
keyCode A key code that represents the button pressed, from KeyEvent.
event The KeyEvent object that defines the button action.
Returns
  • If you handled the event, return true. If you want to allow the event to be handled by the next receiver, return false.

public void onPause ()

Since: API Level 11

Call this to pause any extra processing associated with this WebView and its associated DOM, plugins, JavaScript etc. For example, if the WebView is taken offscreen, this could be called to reduce unnecessary CPU or network traffic. When the WebView is again "active", call onResume(). Note that this differs from pauseTimers(), which affects all WebViews.

public void onResume ()

Since: API Level 11

Call this to resume a WebView after a previous call to onPause().

public boolean onTouchEvent (MotionEvent ev)

Since: API Level 1

Implement this method to handle touch screen motion events.

Parameters
ev The motion event.
Returns
  • True if the event was handled, false otherwise.

public boolean onTrackballEvent (MotionEvent ev)

Since: API Level 1

Implement this method to handle trackball motion events. The relative movement of the trackball since the last event can be retrieve with MotionEvent.getX() and MotionEvent.getY(). These are normalized so that a movement of 1 corresponds to the user pressing one DPAD key (so they will often be fractional values, representing the more fine-grained movement information available from a trackball).

Parameters
ev The motion event.
Returns
  • True if the event was handled, false otherwise.

public void onWindowFocusChanged (boolean hasWindowFocus)

Since: API Level 1

Called when the window containing this view gains or loses focus. Note that this is separate from view focus: to receive key events, both your view and its window must have focus. If a window is displayed on top of yours that takes input focus, then your own window will lose focus but the view focus will remain unchanged.

Parameters
hasWindowFocus True if the window containing this view now has focus, false otherwise.

public boolean overlayHorizontalScrollbar ()

Since: API Level 1

Return whether horizontal scrollbar has overlay style

Returns
  • TRUE if horizontal scrollbar has overlay style.

public boolean overlayVerticalScrollbar ()

Since: API Level 1

Return whether vertical scrollbar has overlay style

Returns
  • TRUE if vertical scrollbar has overlay style.

public boolean pageDown (boolean bottom)

Since: API Level 1

Scroll the contents of the view down by half the page size

Parameters
bottom true to jump to bottom of page
Returns
  • true if the page was scrolled

public boolean pageUp (boolean top)

Since: API Level 1

Scroll the contents of the view up by half the view size

Parameters
top true to jump to the top of the page
Returns
  • true if the page was scrolled

public void pauseTimers ()

Since: API Level 1

Pause all layout, parsing, and JavaScript timers for all webviews. This is a global requests, not restricted to just this webview. This can be useful if the application has been paused.

public boolean performLongClick ()

Since: API Level 1

Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the OnLongClickListener did not consume the event.

Returns
  • True if one of the above receivers consumed the event, false otherwise.

public void postUrl (String url, byte[] postData)

Since: API Level 5

Load the url with postData using "POST" method into the WebView. If url is not a network url, it will be loaded with {link loadUrl(String) instead.

Parameters
url The url of the resource to load.
postData The data will be passed to "POST" request.

public void reload ()

Since: API Level 1

Reload the current url.

public void removeJavascriptInterface (String interfaceName)

Since: API Level 11

Removes a previously added JavaScript interface with the given name.

Parameters
interfaceName The name of the interface to remove.

public boolean requestChildRectangleOnScreen (View child, Rect rect, boolean immediate)

Since: API Level 1

Called when a child of this group wants a particular rectangle to be positioned onto the screen. ViewGroups overriding this can trust that:

  • child will be a direct child of this group
  • rectangle will be in the child's coordinates

ViewGroups overriding this should uphold the contract:

  • nothing will change if the rectangle is already visible
  • the view port will be scrolled only just enough to make the rectangle visible
Parameters
child The direct child making the request.
rect The rectangle in the child's coordinates the child wishes to be on the screen.
immediate True to forbid animated or delayed scrolling, false otherwise
Returns
  • Whether the group scrolled to handle the operation

public boolean requestFocus (int direction, Rect previouslyFocusedRect)

Since: API Level 1

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. The rectangle can help give larger views a finer grained hint about where focus is coming from, and therefore, where to show selection, or forward focus change internally. A view will not actually take focus if it is not focusable (isFocusable() returns false), or if it is focusable and it is not focusable in touch mode (isFocusableInTouchMode()) while the device is in touch mode. A View will not take focus if it is not visible. A View will not take focus if one of its parents has getDescendantFocusability() equal to FOCUS_BLOCK_DESCENDANTS. See also focusSearch(int), which is what you call to say that you have focus, and you want your parent to look for the next one. You may wish to override this method if your custom View has an internal View that it wishes to forward the request to. Looks for a view to give focus to respecting the setting specified by getDescendantFocusability(). Uses onRequestFocusInDescendants(int, android.graphics.Rect) to find focus within the children of this group when appropriate.

Parameters
direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
previouslyFocusedRect The rectangle (in this View's coordinate system) to give a finer grained hint about where focus is coming from. May be null if there is no hint.
Returns
  • Whether this view or one of its descendants actually took focus.

public void requestFocusNodeHref (Message hrefMsg)

Since: API Level 1

Request the anchor or image element URL at the last tapped point. If hrefMsg is null, this method returns immediately and does not dispatch hrefMsg to its target. If the tapped point hits an image, an anchor, or an image in an anchor, the message associates strings in named keys in its data. The value paired with the key may be an empty string.

Parameters
hrefMsg This message will be dispatched with the result of the request. The message data contains three keys: - "url" returns the anchor's href attribute. - "title" returns the anchor's text. - "src" returns the image's src attribute.

public void requestImageRef (Message msg)

Since: API Level 1

Request the url of the image last touched by the user. msg will be sent to its target with a String representing the url as its object.

Parameters
msg This message will be dispatched with the result of the request as the data member with "url" as key. The result can be null.

public boolean restorePicture (Bundle b, File src)

Since: API Level 3

This method is deprecated.
This method is now obsolete.

Restore the display data that was save in savePicture(Bundle, File). Used in conjunction with restoreState(Bundle). Note that this will not work if the WebView is hardware accelerated.

Parameters
b A Bundle containing the saved display data.
src The file where the picture data was stored.
Returns
  • True if the picture was successfully restored.

public WebBackForwardList restoreState (Bundle inState)

Since: API Level 1

Restore the state of this WebView from the given map used in onRestoreInstanceState(Bundle). This method should be called to restore the state of the WebView before using the object. If it is called after the WebView has had a chance to build state (load pages, create a back/forward list, etc.) there may be undesirable side-effects. Please note that this method no longer restores the display data for this WebView. See savePicture(Bundle, File) and restorePicture(Bundle, File) for saving and restoring the display data.

Parameters
inState The incoming Bundle of state.
Returns
  • The restored back/forward list or null if restoreState failed.

public void resumeTimers ()

Since: API Level 1

Resume all layout, parsing, and JavaScript timers for all webviews. This will resume dispatching all timers.

public void savePassword (String host, String username, String password)

Since: API Level 1

Save the username and password for a particular host in the WebView's internal database.

Parameters
host The host that required the credentials.
username The username for the given host.
password The password for the given host.

public boolean savePicture (Bundle b, File dest)

Since: API Level 3

This method is deprecated.
This method is now obsolete.

Save the current display data to the Bundle given. Used in conjunction with saveState(Bundle).

Parameters
b A Bundle to store the display data.
dest The file to store the serialized picture data. Will be overwritten with this WebView's picture data.
Returns
  • True if the picture was successfully saved.

public WebBackForwardList saveState (Bundle outState)

Since: API Level 1

Save the state of this WebView used in onSaveInstanceState(Bundle). Please note that this method no longer stores the display data for this WebView. The previous behavior could potentially leak files if restoreState(Bundle) was never called. See savePicture(Bundle, File) and restorePicture(Bundle, File) for saving and restoring the display data.

Parameters
outState The Bundle to store the WebView state.
Returns
  • The same copy of the back/forward list used to save the state. If saveState fails, the returned list will be null.

public void saveWebArchive (String filename)

Since: API Level 11

Saves the current view as a web archive.

Parameters
filename The filename where the archive should be placed.

public void saveWebArchive (String basename, boolean autoname, ValueCallback<String> callback)

Since: API Level 11

Saves the current view as a web archive.

Parameters
basename The filename where the archive should be placed.
autoname If false, takes basename to be a file. If true, basename is assumed to be a directory in which a filename will be chosen according to the url of the current page.
callback Called after the web archive has been saved. The parameter for onReceiveValue will either be the filename under which the file was saved, or null if saving the file failed.

public void setBackgroundColor (int color)

Since: API Level 1

Set the background color. It's white by default. Pass zero to make the view transparent.

Parameters
color the ARGB color described by Color.java

public void setCertificate (SslCertificate certificate)

Since: API Level 1

Sets the SSL certificate for the main top-level page.

public void setDownloadListener (DownloadListener listener)

Since: API Level 1

Register the interface to be used when content can not be handled by the rendering engine, and should be downloaded instead. This will replace the current handler.

Parameters
listener An implementation of DownloadListener.

public void setHorizontalScrollbarOverlay (boolean overlay)

Since: API Level 1

Specify whether the horizontal scrollbar has overlay style.

Parameters
overlay TRUE if horizontal scrollbar should have overlay style.

public void setHttpAuthUsernamePassword (String host, String realm, String username, String password)

Since: API Level 1

Set the HTTP authentication credentials for a given host and realm.

Parameters
host The host for the credentials.
realm The realm for the credentials.
username The username for the password. If it is null, it means password can't be saved.
password The password

public void setInitialScale (int scaleInPercent)

Since: API Level 1

Set the initial scale for the WebView. 0 means default. If getUseWideViewPort() is true, it zooms out all the way. Otherwise it starts with 100%. If initial scale is greater than 0, WebView starts will this value as initial scale.

Parameters
scaleInPercent The initial scale in percent.

public void setLayoutParams (ViewGroup.LayoutParams params)

Since: API Level 1

Set the layout parameters associated with this view. These supply parameters to the parent of this view specifying how it should be arranged. There are many subclasses of ViewGroup.LayoutParams, and these correspond to the different subclasses of ViewGroup that are responsible for arranging their children.

Parameters
params The layout parameters for this view, cannot be null

public void setMapTrackballToArrowKeys (boolean setMap)

Since: API Level 1

public void setNetworkAvailable (boolean networkUp)

Since: API Level 3

Inform WebView of the network state. This is used to set the JavaScript property window.navigator.isOnline and generates the online/offline event as specified in HTML5, sec. 5.7.7

Parameters
networkUp boolean indicating if network is available

public void setOverScrollMode (int mode)

Since: API Level 9

Set the over-scroll mode for this view. Valid over-scroll modes are OVER_SCROLL_ALWAYS (default), OVER_SCROLL_IF_CONTENT_SCROLLS (allow over-scrolling only if the view content is larger than the container), or OVER_SCROLL_NEVER. Setting the over-scroll mode of a view will have an effect only if the view is capable of scrolling.

Parameters
mode The new over-scroll mode for this view.

public void setPictureListener (WebView.PictureListener listener)

Since: API Level 1

This method is deprecated.
This method is now obsolete.

Set the Picture listener. This is an interface used to receive notifications of a new Picture.

Parameters
listener An implementation of WebView.PictureListener.

public void setScrollBarStyle (int style)

Since: API Level 1

Specify the style of the scrollbars. The scrollbars can be overlaid or inset. When inset, they add to the padding of the view. And the scrollbars can be drawn inside the padding area or on the edge of the view. For example, if a view has a background drawable and you want to draw the scrollbars inside the padding specified by the drawable, you can use SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to appear at the edge of the view, ignoring the padding, then you can use SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.

Parameters
style the style of the scrollbars. Should be one of SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.

public void setVerticalScrollbarOverlay (boolean overlay)

Since: API Level 1

Specify whether the vertical scrollbar has overlay style.

Parameters
overlay TRUE if vertical scrollbar should have overlay style.

public void setWebChromeClient (WebChromeClient client)

Since: API Level 1

Set the chrome handler. This is an implementation of WebChromeClient for use in handling JavaScript dialogs, favicons, titles, and the progress. This will replace the current handler.

Parameters
client An implementation of WebChromeClient.

public void setWebViewClient (WebViewClient client)

Since: API Level 1

Set the WebViewClient that will receive various notifications and requests. This will replace the current handler.

Parameters
client An implementation of WebViewClient.

public boolean shouldDelayChildPressedState ()

Since: API Level 14

Return true if the pressed state should be delayed for children or descendants of this ViewGroup. Generally, this should be done for containers that can scroll, such as a List. This prevents the pressed state from appearing when the user is actually trying to scroll the content. The default implementation returns true for compatibility reasons. Subclasses that do not scroll should generally override this method and return false.

public boolean showFindDialog (String text, boolean showIme)

Since: API Level 11

Start an ActionMode for finding text in this WebView. Only works if this WebView is attached to the view system.

Parameters
text If non-null, will be the initial text to search for. Otherwise, the last String searched for in this WebView will be used to start.
showIme If true, show the IME, assuming the user will begin typing. If false and text is non-null, perform a find all.
Returns
  • boolean True if the find dialog is shown, false otherwise.

public void stopLoading ()

Since: API Level 1

Stop the current load.

public boolean zoomIn ()

Since: API Level 1

Perform zoom in in the webview

Returns
  • TRUE if zoom in succeeds. FALSE if no zoom changes.

public boolean zoomOut ()

Since: API Level 1

Perform zoom out in the webview

Returns
  • TRUE if zoom out succeeds. FALSE if no zoom changes.

Protected Methods

protected int computeHorizontalScrollOffset ()

Since: API Level 1

Compute the horizontal offset of the horizontal scrollbar's thumb within the horizontal range. This value is used to compute the position of the thumb within the scrollbar's track.

The range is expressed in arbitrary units that must be the same as the units used by computeHorizontalScrollRange() and computeHorizontalScrollExtent().

The default offset is the scroll offset of this view.

Returns
  • the horizontal offset of the scrollbar's thumb

protected int computeHorizontalScrollRange ()

Since: API Level 1

Compute the horizontal range that the horizontal scrollbar represents.

The range is expressed in arbitrary units that must be the same as the units used by computeHorizontalScrollExtent() and computeHorizontalScrollOffset().

The default range is the drawing width of this view.

Returns
  • the total horizontal range represented by the horizontal scrollbar

protected int computeVerticalScrollExtent ()

Since: API Level 1

Compute the vertical extent of the horizontal scrollbar's thumb within the vertical range. This value is used to compute the length of the thumb within the scrollbar's track.

The range is expressed in arbitrary units that must be the same as the units used by computeVerticalScrollRange() and computeVerticalScrollOffset().

The default extent is the drawing height of this view.

Returns
  • the vertical extent of the scrollbar's thumb

protected int computeVerticalScrollOffset ()

Since: API Level 1

Compute the vertical offset of the vertical scrollbar's thumb within the horizontal range. This value is used to compute the position of the thumb within the scrollbar's track.

The range is expressed in arbitrary units that must be the same as the units used by computeVerticalScrollRange() and computeVerticalScrollExtent().

The default offset is the scroll offset of this view.

Returns
  • the vertical offset of the scrollbar's thumb

protected int computeVerticalScrollRange ()

Since: API Level 1

Compute the vertical range that the vertical scrollbar represents.

The range is expressed in arbitrary units that must be the same as the units used by computeVerticalScrollExtent() and computeVerticalScrollOffset().

Returns
  • the total vertical range represented by the vertical scrollbar

    The default range is the drawing height of this view.

protected boolean drawChild (Canvas canvas, View child, long drawingTime)

Since: API Level 1

Draw one child of this View Group. This method is responsible for getting the canvas in the right state. This includes clipping, translating so that the child's scrolled origin is at 0, 0, and applying any animation transformations.

Parameters
canvas The canvas on which to draw the child
child Who to draw
drawingTime The time at which draw is occuring
Returns
  • True if an invalidate() was issued

protected void finalize ()

Since: API Level 1

Invoked when the garbage collector has detected that this instance is no longer reachable. The default implementation does nothing, but this method can be overridden to free resources.

Note that objects that override finalize are significantly more expensive than objects that don't. Finalizers may be run a long time after the object is no longer reachable, depending on memory pressure, so it's a bad idea to rely on them for cleanup. Note also that finalizers are run on a single VM-wide finalizer thread, so doing blocking work in a finalizer is a bad idea. A finalizer is usually only necessary for a class that has a native peer and needs to call a native method to destroy that peer. Even then, it's better to provide an explicit close method (and implement Closeable), and insist that callers manually dispose of instances. This works well for something like files, but less well for something like a BigInteger where typical calling code would have to deal with lots of temporaries. Unfortunately, code that creates lots of temporaries is the worst kind of code from the point of view of the single finalizer thread.

If you must use finalizers, consider at least providing your own ReferenceQueue and having your own thread process that queue.

Unlike constructors, finalizers are not automatically chained. You are responsible for calling super.finalize() yourself.

Uncaught exceptions thrown by finalizers are ignored and do not terminate the finalizer thread. See Effective Java Item 7, "Avoid finalizers" for more.

Throws
Throwable

protected void onAttachedToWindow ()

Since: API Level 1

This is called when the view is attached to a window. At this point it has a Surface and will start drawing. Note that this function is guaranteed to be called before onDraw(android.graphics.Canvas), however it may be called any time before the first onDraw -- including before or after onMeasure(int, int).

protected void onConfigurationChanged (Configuration newConfig)

Since: API Level 8

Called when the current configuration of the resources being used by the application have changed. You can use this to decide when to reload resources that can changed based on orientation and other configuration characterstics. You only need to use this if you are not relying on the normal Activity mechanism of recreating the activity instance upon a configuration change.

Parameters
newConfig The new resource configuration.

protected void onDetachedFromWindow ()

Since: API Level 1

This is called when the view is detached from a window. At this point it no longer has a surface for drawing.

protected void onDraw (Canvas canvas)

Since: API Level 1

Implement this to do your drawing.

Parameters
canvas the canvas on which the background will be drawn

protected void onFocusChanged (boolean focused, int direction, Rect previouslyFocusedRect)

Since: API Level 1

Called by the view system when the focus state of this view changes. When the focus change event is caused by directional navigation, direction and previouslyFocusedRect provide insight into where the focus is coming from. When overriding, be sure to call up through to the super class so that the standard focus handling will occur.

Parameters
focused True if the View has focus; false otherwise.
direction The direction focus has moved when requestFocus() is called to give this view focus. Values are FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, or FOCUS_BACKWARD. It may not always apply, in which case use the default.
previouslyFocusedRect The rectangle, in this view's coordinate system, of the previously focused view. If applicable, this will be passed in as finer grained information about where the focus is coming from (in addition to direction). Will be null otherwise.

protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec)

Since: API Level 1

Measure the view and its content to determine the measured width and the measured height. This method is invoked by measure(int, int) and should be overriden by subclasses to provide accurate and efficient measurement of their contents.

CONTRACT: When overriding this method, you must call setMeasuredDimension(int, int) to store the measured width and height of this view. Failure to do so will trigger an IllegalStateException, thrown by measure(int, int). Calling the superclass' onMeasure(int, int) is a valid use.

The base class implementation of measure defaults to the background size, unless a larger size is allowed by the MeasureSpec. Subclasses should override onMeasure(int, int) to provide better measurements of their content.

If this method is overridden, it is the subclass's responsibility to make sure the measured height and width are at least the view's minimum height and width (getSuggestedMinimumHeight() and getSuggestedMinimumWidth()).

Parameters
widthMeasureSpec horizontal space requirements as imposed by the parent. The requirements are encoded with View.MeasureSpec.
heightMeasureSpec vertical space requirements as imposed by the parent. The requirements are encoded with View.MeasureSpec.

protected void onOverScrolled (int scrollX, int scrollY, boolean clampedX, boolean clampedY)

Since: API Level 9

Called by overScrollBy(int, int, int, int, int, int, int, int, boolean) to respond to the results of an over-scroll operation.

Parameters
scrollX New X scroll value in pixels
scrollY New Y scroll value in pixels
clampedX True if scrollX was clamped to an over-scroll boundary
clampedY True if scrollY was clamped to an over-scroll boundary

protected void onScrollChanged (int l, int t, int oldl, int oldt)

Since: API Level 1

This is called in response to an internal scroll in this view (i.e., the view scrolled its own contents). This is typically as a result of scrollBy(int, int) or scrollTo(int, int) having been called.

Parameters
l Current horizontal scroll origin.
t Current vertical scroll origin.
oldl Previous horizontal scroll origin.
oldt Previous vertical scroll origin.

protected void onSizeChanged (int w, int h, int ow, int oh)

Since: API Level 1

This is called during layout when the size of this view has changed. If you were just added to the view hierarchy, you're called with the old values of 0.

Parameters
w Current width of this view.
h Current height of this view.
ow Old width of this view.
oh Old height of this view.

protected void onVisibilityChanged (View changedView, int visibility)

Since: API Level 8

Called when the visibility of the view or an ancestor of the view is changed.

Parameters
changedView The view whose visibility changed. Could be 'this' or an ancestor view.
visibility The new visibility of changedView: VISIBLE, INVISIBLE or GONE.