Android Guides | Samples

Android.Webkit.WebView Class

See Also: WebView

Syntax

[Android.Runtime.Register("android/webkit/WebView", DoNotGenerateAcw=true)]
public class WebView : AbsoluteLayout, ViewGroup+IOnHierarchyChangeListener, ViewTreeObserver+IOnGlobalFocusChangeListener, IDisposable

Remarks

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.

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:

xml Example

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

This must be a child of the element.

For more information, read Building Web Apps in WebView.

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:

java Example

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

java Example

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

java Example

 // 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.

java Example

 // 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://developer.android.com/");

Zoom

Cookie and window management

Building web pages to support 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.
  • 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:

    xml Example

     <link rel="stylesheet" media="screen and (-webkit-device-pixel-ratio:1.5)" href="hdpi.css" />

HTML5 Video support

Full screen support

Layout size

See Intent for more information.

To provide a WebView in your own Activity, include a <WebView> in your layout, or set the entire Activity window as a WebView during Activity.OnCreate(Bundle):

Then load the desired web page:

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

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

To enable the built-in zoom, set WebView.Settings.WebSettings.BuiltInZoomControls (introduced in API level NoType:android/os/Build$VERSION_CODES;Href=../../../reference/android/os/Build.VERSION_CODES.html#CUPCAKE).

NOTE: Using zoom if either the height or width is set to ViewGroup+LayoutParams.WrapContent may lead to undefined behavior and should be avoided.

For obvious security reasons, your application has its own cache, cookie store etc.&mdash;it does not share the Browser application's data.

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.

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 &mdash; sometimes significantly more &mdash; 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 NoType:android/os/Build$VERSION_CODES;Href=../../../reference/android/os/Build.VERSION_CODES.html#ECLAIR, 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 hdpi.css stylesheet is only used for devices with a screen pixel ration of 1.5, which is the high density pixel ratio.

In order to support inline HTML5 video in your application you need to have hardware acceleration turned on.

In order to support full screen &mdash; for video or other HTML content &mdash; you need to set a WebChromeClient and implement both WebChromeClient.OnShowCustomView(Android.Views.View, .ICustomViewCallback) and WebChromeClient.OnHideCustomView. If the implementation of either of these two methods is missing then the web contents will not be allowed to enter full screen. Optionally you can implement WebChromeClient.VideoLoadingProgressView to customize the View displayed whilst a video is loading.

It is recommended to set the WebView layout height to a fixed value or to ViewGroup+LayoutParams.MatchParent instead of using ViewGroup+LayoutParams.WrapContent. When using ViewGroup+LayoutParams.MatchParent for the height none of the WebView's parents should use a ViewGroup+LayoutParams.WrapContent layout height since that could result in incorrect sizing of the views.

Setting the WebView's height to ViewGroup+LayoutParams.WrapContent enables the following behaviors:

  • The HTML body layout height is set to a fixed value. This means that elements with a height relative to the HTML body may not be sized correctly.
  • For applications targetting Build+VERSION_CODES.KitKat and earlier SDKs the HTML viewport meta tag will be ignored in order to preserve backwards compatibility.

Using a layout width of ViewGroup+LayoutParams.WrapContent is not supported. If such a width is used the WebView will attempt to use the width of the parent instead.

[Android Documentation]

Requirements

Namespace: Android.Webkit
Assembly: Mono.Android (in Mono.Android.dll)
Assembly Versions: 0.0.0.0
Since: Added in API level 1

The members of Android.Webkit.WebView are listed below.

See Also: AbsoluteLayout

Public Constructors

Constructs a new WebView with a Context object.
Constructs a new WebView with layout parameters.
Constructs a new WebView with layout parameters and a default style.
Constructs a new WebView with layout parameters and a default style.
Constructs a new WebView with layout parameters and a default style.

Protected Constructors

A constructor used when creating managed representations of JNI objects; called by the runtime.

Public Fields

const
SchemeGeoString. URI scheme for map address.
const
SchemeMailtoString. URI scheme for email address.
const
SchemeTelString. URI scheme for telephone number.

Public Properties

CertificateSslCertificate. Gets the SSL certificate for the main top-level page or null if there is no certificate (the site is not secure).
[read-only]
ContentHeightInt32. Gets the height of the HTML content.
[read-only]
FaviconBitmap. Gets the favicon for the current page.
[read-only]
IsPrivateBrowsingEnabledBoolean. Gets whether private browsing is enabled in this WebView.
[read-only]
OriginalUrlString. Gets the original URL for the current page.
[read-only]
static
PluginListPluginList.
[read-only]
ProgressInt32. Gets the progress for the current page.
[read-only]
ScaleSingle. Gets the current scale of this WebView.
[read-only]
SettingsWebSettings. Gets the WebSettings object used to control the settings for this WebView.
[read-only]
TitleString. Gets the title for the current page.
[read-only]
UrlString. Gets the URL for the current page.
[read-only]
VisibleTitleHeightInt32.
[read-only]
ZoomControlsView.

Protected Properties

[read-only]
override
ThresholdClassIntPtr. This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.
[read-only]
override
ThresholdTypeType. This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.

Public Methods

AddJavascriptInterface(Object, String)
Injects the supplied Java object into this WebView.
CanGoBack() : Boolean
Gets whether this WebView has a back history item.
CanGoBackOrForward(Int32) : Boolean
Gets whether the page can go back or forward the given number of steps.
CanGoForward() : Boolean
Gets whether this WebView has a forward history item.
CanZoomIn() : Boolean
Gets whether this WebView can be zoomed in.
CanZoomOut() : Boolean
Gets whether this WebView can be zoomed out.
CapturePicture() : Picture
Gets a new picture that captures the current contents of this WebView.
ClearCache(Boolean)
Clears the resource cache.
static
ClearClientCertPreferences(IRunnable)
Clears the client certificate preferences stored in response to proceeding/cancelling client cert requests.
ClearFormData()
Removes the autocomplete popup from the currently focused form field, if present.
ClearHistory()
Tells this WebView to clear its internal back/forward list.
ClearMatches()
Clears the highlighting surrounding text matches created by WebView.FindAllAsync(String).
ClearSslPreferences()
Clears the SSL preferences table stored in response to proceeding with SSL certificate errors.
ClearView()
Clears this WebView so that onDraw() will draw nothing but white background, and onMeasure() will return 0 if MeasureSpec is not MeasureSpec.
CopyBackForwardList() : WebBackForwardList
Gets the WebBackForwardList for this WebView.
CreatePrintDocumentAdapter() : PrintDocumentAdapter
CreatePrintDocumentAdapter(String) : PrintDocumentAdapter
Creates a PrintDocumentAdapter that provides the content of this Webview for printing.
DebugDump()
Destroy()
Destroys the internal state of this WebView.
static
DisablePlatformNotifications()
DocumentHasImages(Message)
Queries the document to see if it contains any image references.
EmulateShiftHeld()
static
EnablePlatformNotifications()
static
EnableSlowWholeDocumentDraw()
For apps targeting the L release, WebView has a new default behavior that reduces memory footprint and increases performance by intelligently choosing the portion of the HTML document that needs to be drawn.
EvaluateJavascript(String, IValueCallback)
static
FindAddress(String) : String
Gets the first substring consisting of the address of a physical location.
FindAll(String) : Int32
Finds all instances of find on the page and highlights them.
FindAllAsync(String)
Finds all instances of find on the page and highlights them, asynchronously.
FindNext(Boolean)
Highlights and scrolls to the next match found by WebView.FindAllAsync(String), wrapping around page boundaries as necessary.
FlingScroll(Int32, Int32)
FreeMemory()
Informs this WebView that memory is low so that it can free any available memory.
GetHitTestResult() : WebView+HitTestResult
Gets a HitTestResult based on the current cursor node.
GetHttpAuthUsernamePassword(String, String) : String[]
Retrieves HTTP authentication credentials for a given host and realm.
GoBack()
Goes back in the history of this WebView.
GoBackOrForward(Int32)
Goes to the history item that is the number of steps away from the current item.
GoForward()
Goes forward in the history of this WebView.
InvokeZoomPicker()
Invokes the graphical zoom picker widget for this WebView.
LoadData(String, String, String)
Loads the given data into this WebView using a 'data' scheme URL.
LoadDataWithBaseURL(String, String, String, String, String)
Loads the given data into this WebView, using baseUrl as the base URL for the content.
LoadUrl(String)
Loads the given URL.
LoadUrl(String, IDictionary<string, string>)
OnChildViewAdded(View, View)
Called when a new child is added to a parent view.
OnChildViewRemoved(View, View)
Called when a child is removed from a parent view.
OnGlobalFocusChanged(View, View)
Callback method to be invoked when the focus changes in the view tree.
OnPause()
Pauses any extra processing associated with this WebView and its associated DOM, plugins, JavaScript etc.
OnResume()
Resumes a WebView after a previous call to onPause().
OverlayHorizontalScrollbar() : Boolean
Gets whether horizontal scrollbar has overlay style.
OverlayVerticalScrollbar() : Boolean
Gets whether vertical scrollbar has overlay style.
PageDown(Boolean) : Boolean
Scrolls the contents of this WebView down by half the page size.
PageUp(Boolean) : Boolean
Scrolls the contents of this WebView up by half the view size.
PauseTimers()
Pauses all layout, parsing, and JavaScript timers for all WebViews.
PostUrl(String, Byte[])
Loads the URL with postData using "POST" method into this WebView.
RefreshPlugins(Boolean)
Reload()
Reloads the current URL.
RemoveJavascriptInterface(String)
Removes a previously injected Java object from this WebView.
RequestFocusNodeHref(Message)
Requests the anchor or image element URL at the last tapped point.
RequestImageRef(Message)
Requests 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.
RestorePicture(Bundle, File) : Boolean
RestoreState(Bundle) : WebBackForwardList
Restores the state of this WebView from the given Bundle.
ResumeTimers()
Resumes all layout, parsing, and JavaScript timers for all WebViews.
SavePassword(String, String, String)
Sets a username and password pair for the specified host.
SavePicture(Bundle, File) : Boolean
SaveState(Bundle) : WebBackForwardList
Saves the state of this WebView used in Activity.OnSaveInstanceState(Bundle).
SaveWebArchive(String)
Saves the current view as a web archive.
SaveWebArchive(String, Boolean, IValueCallback)
SetDownloadListener(IDownloadListener)
Registers the interface to be used when content can not be handled by the rendering engine, and should be downloaded instead.
SetFindListener(WebView+IFindListener)
Registers the listener to be notified as find-on-page operations progress.
SetHorizontalScrollbarOverlay(Boolean)
Specifies whether the horizontal scrollbar has overlay style.
SetHttpAuthUsernamePassword(String, String, String, String)
Stores HTTP authentication credentials for a given host and realm.
SetInitialScale(Int32)
Sets the initial scale for this WebView. 0 means default.
SetMapTrackballToArrowKeys(Boolean)
SetNetworkAvailable(Boolean)
Informs WebView of the network state.
SetPictureListener(WebView+IPictureListener)
Sets the Picture listener.
SetVerticalScrollbarOverlay(Boolean)
Specifies whether the vertical scrollbar has overlay style.
SetWebChromeClient(WebChromeClient)
Sets the chrome handler.
static
SetWebContentsDebuggingEnabled(Boolean)
Enables debugging of web contents (HTML / CSS / JavaScript) loaded into any WebViews of this application.
SetWebViewClient(WebViewClient)
Sets the WebViewClient that will receive various notifications and requests.
ShowFindDialog(String, Boolean) : Boolean
Starts an ActionMode for finding text in this WebView.
StopLoading()
Stops the current load.
ZoomBy(Single)
Performs a zoom operation in this WebView.
ZoomIn() : Boolean
Performs zoom in in this WebView.
ZoomOut() : Boolean
Performs zoom out in this WebView.

Public Events