WebView
open class WebView : AbsoluteLayout, ViewTreeObserver.OnGlobalFocusChangeListener, ViewGroup.OnHierarchyChangeListener
kotlin.Any | ||||
↳ | android.view.View | |||
↳ | android.view.ViewGroup | |||
↳ | android.widget.AbsoluteLayout | |||
↳ | android.webkit.WebView |
A View that displays web pages.
Basic usage
In most cases, we recommend using a standard web browser, like Chrome, to deliver content to the user. To learn more about web browsers, read the guide on invoking a browser with an intent.
WebView objects allow you to display web content as part of your activity layout, but lack some of the features of fully-developed browsers. A WebView is useful when you need increased control over the UI and advanced configuration options that will allow you to embed web pages in a specially-designed environment for your app.
To learn more about WebView and alternatives for serving web content, read the documentation on Web-based content.
Summary
Nested classes | |
---|---|
abstract |
Interface to listen for find results. |
open | |
abstract |
Interface to listen for new pictures as they change. |
abstract |
Callback interface supplied to |
open |
Transportation object for returning WebView across thread boundaries. |
Inherited XML attributes | |
---|---|
Constants | |
---|---|
static Int |
The renderer associated with this WebView is bound with the default priority for services. |
static Int |
The renderer associated with this WebView is bound with |
static Int |
The renderer associated with this WebView is bound with |
static String |
URI scheme for map address. |
static String |
URI scheme for email address. |
static String |
URI scheme for telephone number. |
Inherited constants | |
---|---|
Public constructors | |
---|---|
Constructs a new WebView with an Activity Context object. |
|
WebView(context: Context, attrs: AttributeSet?) Constructs a new WebView with layout parameters. |
|
WebView(context: Context, attrs: AttributeSet?, defStyleAttr: Int) Constructs a new WebView with layout parameters and a default style. |
|
WebView(context: Context, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) Constructs a new WebView with layout parameters and a default style. |
|
WebView(context: Context, attrs: AttributeSet?, defStyleAttr: Int, privateBrowsing: Boolean) Constructs a new WebView with layout parameters and a default style. |
Public methods | |
---|---|
open Unit |
addJavascriptInterface(object: Any, name: String) Injects the supplied Java object into this WebView. |
open Unit |
autofill(values: SparseArray<AutofillValue!>) |
open Boolean |
Gets whether this WebView has a back history item. |
open Boolean |
canGoBackOrForward(steps: Int) Gets whether the page can go back or forward the given number of steps. |
open Boolean |
Gets whether this WebView has a forward history item. |
open Boolean |
Gets whether this WebView can be zoomed in. |
open Boolean |
Gets whether this WebView can be zoomed out. |
open Picture! |
Gets a new picture that captures the current contents of this WebView. |
open Unit |
clearCache(includeDiskFiles: Boolean) Clears the resource cache. |
open static Unit |
clearClientCertPreferences(onCleared: Runnable?) Clears the client certificate preferences stored in response to proceeding/cancelling client cert requests. |
open Unit |
Removes the autocomplete popup from the currently focused form field, if present. |
open Unit |
Tells this WebView to clear its internal back/forward list. |
open Unit |
Clears the highlighting surrounding text matches created by |
open Unit |
Clears the SSL preferences table stored in response to proceeding with SSL certificate errors. |
open Unit |
Clears this WebView so that onDraw() will draw nothing but white background, and onMeasure() will return 0 if MeasureSpec is not MeasureSpec. |
open Unit | |
open WebBackForwardList |
Gets the WebBackForwardList for this WebView. |
open PrintDocumentAdapter! | |
open PrintDocumentAdapter |
createPrintDocumentAdapter(documentName: String) Creates a PrintDocumentAdapter that provides the content of this WebView for printing. |
open Array<WebMessagePort!> |
Creates a message channel to communicate with JS and returns the message ports that represent the endpoints of this message channel. |
open Unit |
destroy() Destroys the internal state of this WebView. |
open static Unit |
Indicate that the current process does not intend to use WebView, and that an exception should be thrown if a WebView is created or any other methods in the android. |
open Unit |
dispatchCreateViewTranslationRequest(viewIds: MutableMap<AutofillId!, LongArray!>, supportedFormats: IntArray, capability: TranslationCapability?, requests: MutableList<ViewTranslationRequest!>) Dispatch to collect the |
open Boolean |
dispatchKeyEvent(event: KeyEvent!) |
open Unit |
documentHasImages(response: Message) Queries the document to see if it contains any image references. |
open static Unit |
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. |
open Unit |
evaluateJavascript(script: String, resultCallback: ValueCallback<String!>?) Asynchronously evaluates JavaScript in the context of the currently displayed page. |
open static String? |
findAddress(addr: String!) Gets the first substring which appears to be the address of a physical location. |
open Int |
Finds all instances of find on the page and highlights them. |
open Unit |
findAllAsync(find: String) Finds all instances of find on the page and highlights them, asynchronously. |
open View! | |
open Unit |
Highlights and scrolls to the next match found by |
open Unit |
flingScroll(vx: Int, vy: Int) |
open Unit |
Informs this WebView that memory is low so that it can free any available memory. |
open CharSequence! | |
open AccessibilityNodeProvider! | |
open SslCertificate? |
Gets the SSL certificate for the main top-level page or |
open Int |
Gets the height of the HTML content. |
open static PackageInfo? |
If WebView has already been loaded into the current process this method will return the package that was used to load it. |
open Bitmap? |
Gets the favicon for the current page. |
open Handler! | |
open WebView.HitTestResult |
Gets a HitTestResult based on the current cursor node. |
open Array<String!>? |
getHttpAuthUsernamePassword(host: String!, realm: String!) Retrieves HTTP authentication credentials for a given host and realm from the |
open String? |
Gets the original URL for the current page. |
open Int |
Gets the progress for the current page. |
open Boolean |
Return whether this WebView requests a priority of |
open Int |
Get the requested renderer priority for this WebView. |
open static Uri |
Returns a URL pointing to the privacy policy for Safe Browsing reporting. |
open Float |
getScale() Gets the current scale of this WebView. |
open WebSettings |
Gets the WebSettings object used to control the settings for this WebView. |
open TextClassifier |
Returns the |
open String? |
getTitle() Gets the title for the current page. |
open String? |
getUrl() Gets the URL for the current page. |
open WebChromeClient? |
Gets the chrome handler. |
open static ClassLoader |
Returns the |
open WebViewClient |
Gets the WebViewClient. |
open Looper |
Returns the |
open WebViewRenderProcess? |
Gets a handle to the WebView renderer process associated with this WebView. |
open WebViewRenderProcessClient? |
Gets the renderer client object associated with this WebView. |
open Unit |
goBack() Goes back in the history of this WebView. |
open Unit |
goBackOrForward(steps: Int) Goes to the history item that is the number of steps away from the current item. |
open Unit |
Goes forward in the history of this WebView. |
open Unit |
Invokes the graphical zoom picker widget for this WebView. |
open Boolean |
Gets whether private browsing is enabled in this WebView. |
open Boolean |
isVisibleToUserForAutofill(virtualId: Int) |
open Unit |
Loads the given data into this WebView using a 'data' scheme URL. |
open Unit |
loadDataWithBaseURL(baseUrl: String?, data: String, mimeType: String?, encoding: String?, historyUrl: String?) Loads the given data into this WebView, using baseUrl as the base URL for the content. |
open Unit |
loadUrl(url: String, additionalHttpHeaders: MutableMap<String!, String!>) Loads the given URL with additional HTTP headers, specified as a map from name to value. |
open Unit |
Loads the given URL. |
open WindowInsets! |
onApplyWindowInsets(insets: WindowInsets!) |
open Boolean | |
open Unit |
onChildViewAdded(parent: View!, child: View!) |
open Unit |
onChildViewRemoved(p: View!, child: View!) |
open InputConnection! |
onCreateInputConnection(outAttrs: EditorInfo!) Creates a new InputConnection for an InputMethod to interact with the WebView. |
open Unit |
onCreateVirtualViewTranslationRequests(virtualIds: LongArray, supportedFormats: IntArray, requestsCollector: Consumer<ViewTranslationRequest!>) Collects |
open Boolean |
onDragEvent(event: DragEvent!) |
open Unit | |
open Boolean |
onGenericMotionEvent(event: MotionEvent!) |
open Unit |
onGlobalFocusChanged(oldFocus: View!, newFocus: View!) |
open Boolean |
onHoverEvent(event: MotionEvent!) |
open Boolean | |
open Boolean |
onKeyMultiple(keyCode: Int, repeatCount: Int, event: KeyEvent!) |
open Boolean | |
open Unit |
onPause() Does a best-effort attempt to pause any processing that can be paused safely, such as animations and geolocation. |
open Unit |
onProvideAutofillVirtualStructure(structure: ViewStructure!, flags: Int) Populates a |
open Unit |
onProvideContentCaptureStructure(structure: ViewStructure, flags: Int) Populates a |
open Unit |
onProvideVirtualStructure(structure: ViewStructure!) |
open PointerIcon? |
onResolvePointerIcon(event: MotionEvent, pointerIndex: Int) Resolve the pointer icon that should be used for specified pointer in the motion event. |
open Unit |
onResume() Resumes a WebView after a previous call to |
open Unit | |
open Boolean |
onTouchEvent(event: MotionEvent!) |
open Boolean |
onTrackballEvent(event: MotionEvent!) |
open Unit |
Called when the content from |
open Unit |
onWindowFocusChanged(hasWindowFocus: Boolean) |
open Boolean |
Gets whether horizontal scrollbar has overlay style. |
open Boolean |
Gets whether vertical scrollbar has overlay style. |
open Boolean |
Scrolls the contents of this WebView down by half the page size. |
open Boolean |
Scrolls the contents of this WebView up by half the view size. |
open Unit |
Pauses all layout, parsing, and JavaScript timers for all WebViews. |
open Boolean | |
open Unit |
Loads the URL with postData using "POST" method into this WebView. |
open Unit |
postVisualStateCallback(requestId: Long, callback: WebView.VisualStateCallback) Posts a |
open Unit |
postWebMessage(message: WebMessage, targetOrigin: Uri) Post a message to main frame. |
open Unit |
reload() Reloads the current URL. |
open Unit |
removeJavascriptInterface(name: String) Removes a previously injected Java object from this WebView. |
open Boolean |
requestChildRectangleOnScreen(child: View, rect: Rect!, immediate: Boolean) |
open Boolean |
requestFocus(direction: Int, previouslyFocusedRect: Rect!) |
open Unit |
requestFocusNodeHref(hrefMsg: Message?) Requests the anchor or image element URL at the last tapped point. |
open Unit |
requestImageRef(msg: Message) Requests the URL of the image last touched by the user. |
open WebBackForwardList? |
restoreState(inState: Bundle) Restores the state of this WebView from the given Bundle. |
open Unit |
Resumes all layout, parsing, and JavaScript timers for all WebViews. |
open Unit |
savePassword(host: String!, username: String!, password: String!) Sets a username and password pair for the specified host. |
open WebBackForwardList? |
Saves the state of this WebView used in android. |
open Unit |
saveWebArchive(filename: String) Saves the current view as a web archive. |
open Unit |
saveWebArchive(basename: String, autoname: Boolean, callback: ValueCallback<String!>?) Saves the current view as a web archive. |
open Unit |
setBackgroundColor(color: Int) |
open Unit |
setCertificate(certificate: SslCertificate!) Sets the SSL certificate for the main top-level page. |
open static Unit |
setDataDirectorySuffix(suffix: String) Define the directory used to store WebView data for the current process. |
open Unit |
setDownloadListener(listener: DownloadListener?) Registers the interface to be used when content can not be handled by the rendering engine, and should be downloaded instead. |
open Unit |
setFindListener(listener: WebView.FindListener?) Registers the listener to be notified as find-on-page operations progress. |
open Unit |
setHorizontalScrollbarOverlay(overlay: Boolean) Specifies whether the horizontal scrollbar has overlay style. |
open Unit |
setHttpAuthUsernamePassword(host: String!, realm: String!, username: String!, password: String!) Stores HTTP authentication credentials for a given host and realm to the |
open Unit |
setInitialScale(scaleInPercent: Int) Sets the initial scale for this WebView. |
open Unit |
setLayerType(layerType: Int, paint: Paint?) |
open Unit |
setLayoutParams(params: ViewGroup.LayoutParams!) |
open Unit |
setMapTrackballToArrowKeys(setMap: Boolean) |
open Unit |
setNetworkAvailable(networkUp: Boolean) Informs WebView of the network state. |
open Unit |
setOverScrollMode(mode: Int) |
open Unit |
setPictureListener(listener: WebView.PictureListener!) Sets the Picture listener. |
open Unit |
setRendererPriorityPolicy(rendererRequestedPriority: Int, waivedWhenNotVisible: Boolean) Set the renderer priority policy for this |
open static Unit |
setSafeBrowsingWhitelist(hosts: MutableList<String!>, callback: ValueCallback<Boolean!>?) Sets the list of hosts (domain names/IP addresses) that are exempt from SafeBrowsing checks. |
open Unit |
setScrollBarStyle(style: Int) |
open Unit |
setTextClassifier(textClassifier: TextClassifier?) Sets the |
open Unit |
setVerticalScrollbarOverlay(overlay: Boolean) Specifies whether the vertical scrollbar has overlay style. |
open Unit |
setWebChromeClient(client: WebChromeClient?) Sets the chrome handler. |
open static Unit |
setWebContentsDebuggingEnabled(enabled: Boolean) Enables debugging of web contents (HTML / CSS / JavaScript) loaded into any WebViews of this application. |
open Unit |
setWebViewClient(client: WebViewClient) Sets the WebViewClient that will receive various notifications and requests. |
open Unit |
setWebViewRenderProcessClient(executor: Executor, webViewRenderProcessClient: WebViewRenderProcessClient) Sets the renderer client object associated with this WebView. |
open Unit |
setWebViewRenderProcessClient(webViewRenderProcessClient: WebViewRenderProcessClient?) Sets the renderer client object associated with this WebView. |
open Boolean | |
open Boolean |
showFindDialog(text: String?, showIme: Boolean) Starts an ActionMode for finding text in this WebView. |
open static Unit |
startSafeBrowsing(context: Context, callback: ValueCallback<Boolean!>?) Starts Safe Browsing initialization. |
open Unit |
Stops the current load. |
open Unit |
Performs a zoom operation in this WebView. |
open Boolean |
zoomIn() Performs zoom in in this WebView. |
open Boolean |
zoomOut() Performs zoom out in this WebView. |
Protected methods | |
---|---|
open Int | |
open Int | |
open Int | |
open Int | |
open Int | |
open Unit |
dispatchDraw(canvas: Canvas) |
open Unit | |
open Unit |
onConfigurationChanged(newConfig: Configuration!) |
open Unit | |
open Unit |
onFocusChanged(focused: Boolean, direction: Int, previouslyFocusedRect: Rect?) |
open Unit | |
open Unit |
onOverScrolled(scrollX: Int, scrollY: Int, clampedX: Boolean, clampedY: Boolean) |
open Unit |
onScrollChanged(l: Int, t: Int, oldl: Int, oldt: Int) |
open Unit |
onSizeChanged(w: Int, h: Int, ow: Int, oh: Int) |
open Unit |
onVisibilityChanged(changedView: View, visibility: Int) |
open Unit |
onWindowVisibilityChanged(visibility: Int) |
Inherited functions | |
---|---|
Inherited properties | |
---|---|
Constants
RENDERER_PRIORITY_BOUND
static val RENDERER_PRIORITY_BOUND: Int
The renderer associated with this WebView is bound with the default priority for services. Use with setRendererPriorityPolicy
.
Value: 1
RENDERER_PRIORITY_IMPORTANT
static val RENDERER_PRIORITY_IMPORTANT: Int
The renderer associated with this WebView is bound with Context#BIND_IMPORTANT
. Use with setRendererPriorityPolicy
.
Value: 2
RENDERER_PRIORITY_WAIVED
static val RENDERER_PRIORITY_WAIVED: Int
The renderer associated with this WebView is bound with Context#BIND_WAIVE_PRIORITY
. At this priority level WebView
renderers will be strong targets for out of memory killing. Use with setRendererPriorityPolicy
.
Value: 0
SCHEME_GEO
static val SCHEME_GEO: String
URI scheme for map address.
Value: "geo:0,0?q="
SCHEME_MAILTO
static val SCHEME_MAILTO: String
URI scheme for email address.
Value: "mailto:"
SCHEME_TEL
static val SCHEME_TEL: String
URI scheme for telephone number.
Value: "tel:"
Public constructors
WebView
WebView(context: Context)
Constructs a new WebView with an Activity Context object.
Note: WebView should always be instantiated with an Activity Context. If instantiated with an Application Context, WebView will be unable to provide several features, such as JavaScript dialogs and autofill.
Parameters | |
---|---|
context |
Context: an Activity Context to access application assets This value cannot be null . |
WebView
WebView(
context: Context,
attrs: AttributeSet?)
Constructs a new WebView with layout parameters.
Parameters | |
---|---|
context |
Context: an Activity Context to access application assets This value cannot be null . |
attrs |
AttributeSet?: an AttributeSet passed to our parent This value may be null . |
WebView
WebView(
context: Context,
attrs: AttributeSet?,
defStyleAttr: Int)
Constructs a new WebView with layout parameters and a default style.
Parameters | |
---|---|
context |
Context: an Activity Context to access application assets This value cannot be null . |
attrs |
AttributeSet?: an AttributeSet passed to our parent This value may be null . |
defStyleAttr |
Int: an attribute in the current theme that contains a reference to a style resource that supplies default values for the view. Can be 0 to not look for defaults. |
WebView
WebView(
context: Context,
attrs: AttributeSet?,
defStyleAttr: Int,
defStyleRes: Int)
Constructs a new WebView with layout parameters and a default style.
Parameters | |
---|---|
context |
Context: an Activity Context to access application assets This value cannot be null . |
attrs |
AttributeSet?: an AttributeSet passed to our parent This value may be null . |
defStyleAttr |
Int: an attribute in the current theme that contains a reference to a style resource that supplies default values for the view. Can be 0 to not look for defaults. |
defStyleRes |
Int: a resource identifier of a style resource that supplies default values for the view, used only if defStyleAttr is 0 or can not be found in the theme. Can be 0 to not look for defaults. |
WebView
WebView(
context: Context,
attrs: AttributeSet?,
defStyleAttr: Int,
privateBrowsing: Boolean)
Deprecated: Private browsing is no longer supported directly via WebView and will be removed in a future release. Prefer using WebSettings
, WebViewDatabase
, CookieManager
and WebStorage
for fine-grained control of privacy data.
Constructs a new WebView with layout parameters and a default style.
Parameters | |
---|---|
context |
Context: an Activity Context to access application assets This value cannot be null . |
attrs |
AttributeSet?: an AttributeSet passed to our parent This value may be null . |
defStyleAttr |
Int: an attribute in the current theme that contains a reference to a style resource that supplies default values for the view. Can be 0 to not look for defaults. |
privateBrowsing |
Boolean: whether this WebView will be initialized in private mode |
Public methods
addJavascriptInterface
open fun addJavascriptInterface(
object: Any,
name: String
): Unit
Injects the supplied Java object into this WebView. The object is injected into all frames of the web page, including all the iframes, using the supplied name. This allows the Java object's methods to be accessed from JavaScript. For applications targeted to API level android.os.Build.VERSION_CODES#JELLY_BEAN_MR1
and above, only public methods that are annotated with android.webkit.JavascriptInterface
can be accessed from JavaScript. For applications targeted to API level android.os.Build.VERSION_CODES#JELLY_BEAN
or below, all public methods (including the inherited ones) can be accessed, see the important security note below for implications.
Note that injected objects will not appear in JavaScript until the page is next (re)loaded. JavaScript should be enabled before injecting the object. For example:
class JsObject { @JavascriptInterface public String toString() { return "injectedObject"; } } webview.getSettings().setJavaScriptEnabled(true); webView.addJavascriptInterface(new JsObject(), "injectedObject"); webView.loadData("<title></title>", "text/html", null); webView.loadUrl("javascript:alert(injectedObject.toString())");
IMPORTANT:
- This method can be used to allow JavaScript to control the host application. This is a powerful feature, but also presents a security risk for apps targeting
android.os.Build.VERSION_CODES#JELLY_BEAN
or earlier. Apps that target a version later thanandroid.os.Build.VERSION_CODES#JELLY_BEAN
are still vulnerable if the app runs on a device running Android earlier than 4.2. The most secure way to use this method is to targetandroid.os.Build.VERSION_CODES#JELLY_BEAN_MR1
and to ensure the method is called only when running on Android 4.2 or later. With these older versions, JavaScript could use reflection to access an injected object's public fields. Use of this method in a WebView containing untrusted content could allow an attacker to manipulate the host application in unintended ways, executing Java code with the permissions of the host application. Use extreme care when using this method in a WebView which could contain untrusted content. - JavaScript interacts with Java object on a private, background thread of this WebView. Care is therefore required to maintain thread safety.
- Because the object is exposed to all the frames, any frame could obtain the object name and call methods on it. There is no way to tell the calling frame's origin from the app side, so the app must not assume that the caller is trustworthy unless the app can guarantee that no third party content is ever loaded into the WebView even inside an iframe.
- The Java object's fields are not accessible.
- For applications targeted to API level
android.os.Build.VERSION_CODES#LOLLIPOP
and above, methods of injected Java objects are enumerable from JavaScript.
Parameters | |
---|---|
object |
Any: the Java object to inject into this WebView's JavaScript context. null values are ignored. |
name |
String: the name used to expose the object in JavaScript This value cannot be null . |
autofill
open fun autofill(values: SparseArray<AutofillValue!>): Unit
Parameters | |
---|---|
values |
SparseArray<AutofillValue!>: map of values to be autofilled, keyed by virtual child id. This value cannot be null . |
canGoBack
open fun canGoBack(): Boolean
Gets whether this WebView has a back history item.
Return | |
---|---|
Boolean |
true if this WebView has a back history item |
canGoBackOrForward
open fun canGoBackOrForward(steps: Int): Boolean
Gets whether the page can go back or forward the given number of steps.
Parameters | |
---|---|
steps |
Int: the negative or positive number of steps to move the history |
canGoForward
open fun canGoForward(): Boolean
Gets whether this WebView has a forward history item.
Return | |
---|---|
Boolean |
true if this WebView has a forward history item |
canZoomIn
open funcanZoomIn(): Boolean
Deprecated: This method is prone to inaccuracy due to race conditions between the web rendering and UI threads; prefer WebViewClient#onScaleChanged
.
Gets whether this WebView can be zoomed in.
Return | |
---|---|
Boolean |
true if this WebView can be zoomed in |
canZoomOut
open funcanZoomOut(): Boolean
Deprecated: This method is prone to inaccuracy due to race conditions between the web rendering and UI threads; prefer WebViewClient#onScaleChanged
.
Gets whether this WebView can be zoomed out.
Return | |
---|---|
Boolean |
true if this WebView can be zoomed out |
capturePicture
open funcapturePicture(): Picture!
Deprecated: Use onDraw
to obtain a bitmap snapshot of the WebView, or #saveWebArchive to save the content to a file.
Gets a new picture that captures the current contents of this WebView. The picture is of the entire document being displayed, and is not limited to the area currently displayed by this WebView. Also, the picture is a static copy and is unaffected by later changes to the content being displayed.
Note that due to internal changes, for API levels between android.os.Build.VERSION_CODES#HONEYCOMB
and android.os.Build.VERSION_CODES#ICE_CREAM_SANDWICH
inclusive, the picture does not include fixed position elements or scrollable divs.
Note that from android.os.Build.VERSION_CODES#JELLY_BEAN_MR1
the returned picture should only be drawn into bitmap-backed Canvas - using any other type of Canvas will involve additional conversion at a cost in memory and performance.
Return | |
---|---|
Picture! |
a picture that captures the current contents of this WebView |
clearCache
open fun clearCache(includeDiskFiles: Boolean): Unit
Clears the resource cache. Note that the cache is per-application, so this will clear the cache for all WebViews used.
Parameters | |
---|---|
includeDiskFiles |
Boolean: if false , only the RAM cache is cleared |
clearClientCertPreferences
open static fun clearClientCertPreferences(onCleared: Runnable?): Unit
Clears the client certificate preferences stored in response to proceeding/cancelling client cert requests. Note that WebView automatically clears these preferences when the system keychain is updated. The preferences are shared by all the WebViews that are created by the embedder application.
Parameters | |
---|---|
onCleared |
Runnable?: A runnable to be invoked when client certs are cleared. The runnable will be called in UI thread. This value may be null . |
clearFormData
open fun clearFormData(): Unit
Removes the autocomplete popup from the currently focused form field, if present. Note this only affects the display of the autocomplete popup, it does not remove any saved form data from this WebView's store. To do that, use WebViewDatabase#clearFormData
.
clearHistory
open fun clearHistory(): Unit
Tells this WebView to clear its internal back/forward list.
clearMatches
open fun clearMatches(): Unit
Clears the highlighting surrounding text matches created by findAllAsync
.
clearSslPreferences
open fun clearSslPreferences(): Unit
Clears the SSL preferences table stored in response to proceeding with SSL certificate errors.
clearView
open funclearView(): Unit
Deprecated: Use WebView.loadUrl("about:blank") to reliably reset the view state and release page resources (including any running JavaScript).
Clears this WebView so that onDraw() will draw nothing but white background, and onMeasure() will return 0 if MeasureSpec is not MeasureSpec.EXACTLY.
copyBackForwardList
open fun copyBackForwardList(): WebBackForwardList
Gets 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.
Return | |
---|---|
WebBackForwardList |
This value cannot be null . |
createPrintDocumentAdapter
open funcreatePrintDocumentAdapter(): PrintDocumentAdapter!
Deprecated: Use createPrintDocumentAdapter(java.lang.String)
which requires user to provide a print document name.
createPrintDocumentAdapter
open fun createPrintDocumentAdapter(documentName: String): PrintDocumentAdapter
Creates a PrintDocumentAdapter that provides the content of this WebView for printing. The adapter works by converting the WebView contents to a PDF stream. The WebView cannot be drawn during the conversion process - any such draws are undefined. It is recommended to use a dedicated off screen WebView for the printing. If necessary, an application may temporarily hide a visible WebView by using a custom PrintDocumentAdapter instance wrapped around the object returned and observing the onStart and onFinish methods. See android.print.PrintDocumentAdapter
for more information.
Parameters | |
---|---|
documentName |
String: The user-facing name of the printed document. See android.print.PrintDocumentInfo This value cannot be null . |
Return | |
---|---|
PrintDocumentAdapter |
This value cannot be null . |
createWebMessageChannel
open fun createWebMessageChannel(): Array<WebMessagePort!>
Creates a message channel to communicate with JS and returns the message ports that represent the endpoints of this message channel. The HTML5 message channel functionality is described here
The returned message channels are entangled and already in started state.
Return | |
---|---|
Array<WebMessagePort!> |
the two message ports that form the message channel. This value cannot be null . |
destroy
open fun destroy(): Unit
Destroys the internal state of this WebView. This method should be called after this WebView has been removed from the view system. No other methods may be called on this WebView after destroy.
disableWebView
open static fun disableWebView(): Unit
Indicate that the current process does not intend to use WebView, and that an exception should be thrown if a WebView is created or any other methods in the android.webkit package are used.
Applications with multiple processes may wish to call this in processes that are not intended to use WebView to avoid accidentally incurring the memory usage of initializing WebView in long-lived processes that have no need for it, and to prevent potential data directory conflicts (see setDataDirectorySuffix
).
For example, an audio player application with one process for its activities and another process for its playback service may wish to call this method in the playback service's android.app.Service#onCreate
.
Exceptions | |
---|---|
java.lang.IllegalStateException |
if WebView has already been initialized in the current process. |
dispatchCreateViewTranslationRequest
open fun dispatchCreateViewTranslationRequest(
viewIds: MutableMap<AutofillId!, LongArray!>,
supportedFormats: IntArray,
capability: TranslationCapability?,
requests: MutableList<ViewTranslationRequest!>
): Unit
Dispatch to collect the ViewTranslationRequest
s for translation purpose by traversing the hierarchy when the app requests ui translation. Typically, this method should only be overridden by subclasses that provide a view hierarchy (such as ViewGroup
). Other classes should override View#onCreateViewTranslationRequest
for normal view or override View#onVirtualViewTranslationResponses
for view contains virtual children. When requested to start the ui translation, the system will call this method to traverse the view hierarchy to collect ViewTranslationRequest
s and create a android.view.translation.Translator
to translate the requests. All the ViewTranslationRequest
s must be added when the traversal is done.
The default implementation calls View#onCreateViewTranslationRequest
for normal view or calls View#onVirtualViewTranslationResponses
for view contains virtual children to build ViewTranslationRequest
if the view should be translated. The view is marked as having transient state
so that recycling of views doesn't prevent the system from attaching the response to it. Therefore, if overriding this method, you should set or reset the transient state.
dispatchCreateViewTranslationRequest
for all the child views.
Parameters | |
---|---|
viewIds |
MutableMap<AutofillId!, LongArray!>: This value cannot be null . |
supportedFormats |
IntArray: This value cannot be null . Value is android.view.translation.TranslationSpec#DATA_FORMAT_TEXT |
capability |
TranslationCapability?: This value may be null . |
requests |
MutableList<ViewTranslationRequest!>: This value cannot be null . |
dispatchKeyEvent
open fun dispatchKeyEvent(event: KeyEvent!): Boolean
Parameters | |
---|---|
event |
KeyEvent!: The key event to be dispatched. |
Return | |
---|---|
Boolean |
True if the event was handled, false otherwise. |
documentHasImages
open fun documentHasImages(response: Message): Unit
Queries 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 |
Message: the message that will be dispatched with the result This value cannot be null . |
enableSlowWholeDocumentDraw
open static fun enableSlowWholeDocumentDraw(): Unit
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. These optimizations are transparent to the developers. However, under certain circumstances, an App developer may want to disable them:
- When an app uses
onDraw
to do own drawing and accesses portions of the page that is way outside the visible portion of the page. - When an app uses
capturePicture
to capture a very large HTML document. Note that capturePicture is a deprecated API.
evaluateJavascript
open fun evaluateJavascript(
script: String,
resultCallback: ValueCallback<String!>?
): Unit
Asynchronously evaluates JavaScript in the context of the currently displayed page. If non-null, resultCallback
will be invoked with any result returned from that execution. This method must be called on the UI thread and the callback will be made on the UI thread.
Compatibility note. Applications targeting android.os.Build.VERSION_CODES#N
or later, JavaScript state from an empty WebView is no longer persisted across navigations like loadUrl(java.lang.String)
. For example, global variables and functions defined before calling loadUrl(java.lang.String)
will not exist in the loaded page. Applications should use addJavascriptInterface
instead to persist JavaScript objects across navigations.
Parameters | |
---|---|
script |
String: the JavaScript to execute. This value cannot be null . |
resultCallback |
ValueCallback<String!>?: A callback to be invoked when the script execution completes with the result of the execution (if any). May be null if no notification of the result is required. |
findAddress
open static funfindAddress(addr: String!): String?
Deprecated: This method is superseded by TextClassifier#generateLinks(
. Avoid using this method even when targeting API levels where no alternative is available.
Gets the first substring which appears to be the address of a physical location. Only addresses in the United States can be detected, which must 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
Note: This function is deprecated and should be avoided on all API levels, as it cannot detect addresses outside of the United States and has a high rate of false positives. On API level android.os.Build.VERSION_CODES#O_MR1
and earlier, it also causes the entire WebView implementation to be loaded and initialized, which can throw android.util.AndroidRuntimeException
or other exceptions if the WebView implementation is currently being updated.
Parameters | |
---|---|
addr |
String!: the string to search for addresses |
Return | |
---|---|
String? |
the address, or if no address is found, null |
findAll
open funfindAll(find: String!): Int
Deprecated: findAllAsync
is preferred.
Finds all instances of find on the page and highlights them. Notifies any registered FindListener
.
Parameters | |
---|---|
find |
String!: the string to find |
Return | |
---|---|
Int |
the number of occurrences of the String "find" that were found |
See Also
findAllAsync
open fun findAllAsync(find: String): Unit
Finds all instances of find on the page and highlights them, asynchronously. Notifies any registered FindListener
. Successive calls to this will cancel any pending searches.
Parameters | |
---|---|
find |
String: the string to find. This value cannot be null . |
See Also
findFocus
open fun findFocus(): View!
Return | |
---|---|
View! |
The view that currently has focus, or null if no focused view can be found. |
findNext
open fun findNext(forward: Boolean): Unit
Highlights and scrolls to the next match found by findAllAsync
, wrapping around page boundaries as necessary. Notifies any registered FindListener
. If findAllAsync(java.lang.String)
has not been called yet, or if clearMatches
has been called since the last find operation, this function does nothing.
Parameters | |
---|---|
forward |
Boolean: the direction to search |
See Also
freeMemory
open funfreeMemory(): Unit
Deprecated: Memory caches are automatically dropped when no longer needed, and in response to system memory pressure.
Informs this WebView that memory is low so that it can free any available memory.
getAccessibilityNodeProvider
open fun getAccessibilityNodeProvider(): AccessibilityNodeProvider!
Return | |
---|---|
AccessibilityNodeProvider! |
The provider. |
getCertificate
open fun getCertificate(): SslCertificate?
Gets the SSL certificate for the main top-level page or null
if there is no certificate (the site is not secure).
Return | |
---|---|
SslCertificate? |
the SSL certificate for the main top-level page |
getContentHeight
open fun getContentHeight(): Int
Gets the height of the HTML content.
Return | |
---|---|
Int |
the height of the HTML content |
getCurrentWebViewPackage
open static fun getCurrentWebViewPackage(): PackageInfo?
If WebView has already been loaded into the current process this method will return the package that was used to load it. Otherwise, the package that would be used if the WebView was loaded right now will be returned; this does not cause WebView to be loaded, so this information may become outdated at any time. The WebView package changes either when the current WebView package is updated, disabled, or uninstalled. It can also be changed through a Developer Setting. If the WebView package changes, any app process that has loaded WebView will be killed. The next time the app starts and loads WebView it will use the new WebView package instead.
Return | |
---|---|
PackageInfo? |
the current WebView package, or null if there is none. |
getFavicon
open fun getFavicon(): Bitmap?
Gets the favicon for the current page. This is the favicon of the current page until WebViewClient.onReceivedIcon is called.
Return | |
---|---|
Bitmap? |
the favicon for the current page or null if the page doesn't have one or if no page has been loaded |
getHandler
open fun getHandler(): Handler!
Return | |
---|---|
Handler! |
A handler associated with the thread running the View. This handler can be used to pump events in the UI events queue. |
getHitTestResult
open fun getHitTestResult(): WebView.HitTestResult
Gets 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
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.
Return | |
---|---|
WebView.HitTestResult |
This value cannot be null . |
getHttpAuthUsernamePassword
open fungetHttpAuthUsernamePassword(
host: String!,
realm: String!
): Array<String!>?
Deprecated: Use WebViewDatabase#getHttpAuthUsernamePassword
instead
Retrieves HTTP authentication credentials for a given host and realm from the WebViewDatabase
instance.
Parameters | |
---|---|
host |
String!: the host to which the credentials apply |
realm |
String!: the realm to which the credentials apply |
Return | |
---|---|
Array<String!>? |
the credentials as a String array, if found. The first element is the username and the second element is the password. null if no credentials are found. |
getOriginalUrl
open fun getOriginalUrl(): String?
Gets 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.
Return | |
---|---|
String? |
the URL that was originally requested for the current page or null if no page has been loaded |
getProgress
open fun getProgress(): Int
Gets the progress for the current page.
Return | |
---|---|
Int |
the progress for the current page between 0 and 100 |
getRendererPriorityWaivedWhenNotVisible
open fun getRendererPriorityWaivedWhenNotVisible(): Boolean
Return whether this WebView requests a priority of RENDERER_PRIORITY_WAIVED
when not visible.
Return | |
---|---|
Boolean |
whether this WebView requests a priority of RENDERER_PRIORITY_WAIVED when not visible. |
getRendererRequestedPriority
open fun getRendererRequestedPriority(): Int
Get the requested renderer priority for this WebView.
Return | |
---|---|
Int |
the requested renderer priority policy. Value is android.webkit.WebView#RENDERER_PRIORITY_WAIVED , android.webkit.WebView#RENDERER_PRIORITY_BOUND , or android.webkit.WebView#RENDERER_PRIORITY_IMPORTANT |
getSafeBrowsingPrivacyPolicyUrl
open static fun getSafeBrowsingPrivacyPolicyUrl(): Uri
Returns a URL pointing to the privacy policy for Safe Browsing reporting.
Return | |
---|---|
Uri |
the url pointing to a privacy policy document which can be displayed to users. This value cannot be null . |
getScale
open fungetScale(): Float
Deprecated: This method is prone to inaccuracy due to race conditions between the web rendering and UI threads; prefer WebViewClient#onScaleChanged
.
Gets the current scale of this WebView.
Return | |
---|---|
Float |
the current scale |
getSettings
open fun getSettings(): WebSettings
Gets the WebSettings object used to control the settings for this WebView.
Return | |
---|---|
WebSettings |
a WebSettings object that can be used to control this WebView's settings This value cannot be null . |
getTextClassifier
open fun getTextClassifier(): TextClassifier
Returns the TextClassifier
used by this WebView. If no TextClassifier has been set, this WebView uses the default set by the system.
Return | |
---|---|
TextClassifier |
This value cannot be null . |
getTitle
open fun getTitle(): String?
Gets the title for the current page. This is the title of the current page until WebViewClient.onReceivedTitle is called.
Return | |
---|---|
String? |
the title for the current page or null if no page has been loaded |
getUrl
open fun getUrl(): String?
Gets 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.
Return | |
---|---|
String? |
the URL for the current page or null if no page has been loaded |
getWebChromeClient
open fun getWebChromeClient(): WebChromeClient?
Gets the chrome handler.
Return | |
---|---|
WebChromeClient? |
the WebChromeClient, or null if not yet set |
See Also
getWebViewClassLoader
open static fun getWebViewClassLoader(): ClassLoader
Returns the ClassLoader
used to load internal WebView classes. This method is meant for use by the WebView Support Library, there is no reason to use this method otherwise.
Return | |
---|---|
ClassLoader |
This value cannot be null . |
getWebViewClient
open fun getWebViewClient(): WebViewClient
Gets the WebViewClient.
Return | |
---|---|
WebViewClient |
the WebViewClient, or a default client if not yet set This value cannot be null . |
See Also
getWebViewLooper
open fun getWebViewLooper(): Looper
Returns the Looper
corresponding to the thread on which WebView calls must be made.
Return | |
---|---|
Looper |
This value cannot be null . |
getWebViewRenderProcess
open fun getWebViewRenderProcess(): WebViewRenderProcess?
Gets a handle to the WebView renderer process associated with this WebView.
In android.os.Build.VERSION_CODES#O
and above, WebView may run in "multiprocess" mode. In multiprocess mode, rendering of web content is performed by a sandboxed renderer process separate to the application process. This renderer process may be shared with other WebViews in the application, but is not shared with other application processes.
If WebView is running in multiprocess mode, this method returns a handle to the renderer process associated with the WebView, which can be used to control the renderer process.
Return | |
---|---|
WebViewRenderProcess? |
the WebViewRenderProcess renderer handle associated with this WebView , or null if WebView is not runing in multiprocess mode. |
getWebViewRenderProcessClient
open fun getWebViewRenderProcessClient(): WebViewRenderProcessClient?
Gets the renderer client object associated with this WebView.
Return | |
---|---|
WebViewRenderProcessClient? |
the WebViewRenderProcessClient object associated with this WebView, if one has been set via setWebViewRenderProcessClient(android.webkit.WebViewRenderProcessClient) or null otherwise. |
goBackOrForward
open fun goBackOrForward(steps: Int): Unit
Goes 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 |
Int: the number of steps to take back or forward in the back forward list |
goForward
open fun goForward(): Unit
Goes forward in the history of this WebView.
invokeZoomPicker
open fun invokeZoomPicker(): Unit
Invokes 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.
isPrivateBrowsingEnabled
open fun isPrivateBrowsingEnabled(): Boolean
Gets whether private browsing is enabled in this WebView.
isVisibleToUserForAutofill
open fun isVisibleToUserForAutofill(virtualId: Int): Boolean
Return | |
---|---|
Boolean |
Whether the view is visible on the screen. |
loadData
open fun loadData(
data: String,
mimeType: String?,
encoding: String?
): Unit
Loads the given data into this 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.
The encoding
parameter specifies whether the data is base64 or URL encoded. If the data is base64 encoded, the value of the encoding parameter must be "base64"
. HTML can be encoded with android.util.Base64#encodeToString(byte[],int)
like so:
String unencodedHtml = "<html><body>'%28' is the code for '('</body></html>"; String encodedHtml = Base64.encodeToString(unencodedHtml.getBytes(), Base64.NO_PADDING); webView.loadData(encodedHtml, "text/html", "base64");
For all other values of encoding
(including null
) it is assumed that the data uses 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. See RFC 3986 for more information. Applications targeting android.os.Build.VERSION_CODES#Q
or later must either use base64 or encode any characters in the content as
%23
, otherwise they will be treated as the end of the content and the remaining text used as a document fragment identifier.
The mimeType
parameter specifies the format of the data. If WebView can't handle the specified MIME type, it will download the data. If null
, defaults to 'text/html'.
The 'data' scheme URL formed by this method uses the default US-ASCII charset. If you 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(java.lang.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.
Content loaded using this method will have a window.origin
value of "null"
. This must not be considered to be a trusted origin by the application or by any JavaScript code running inside the WebView (for example, event sources in DOM event handlers or web messages), because malicious content can also create frames with a null origin. If you need to identify the main frame's origin in a trustworthy way, you should use loadDataWithBaseURL()
with a valid HTTP or HTTPS base URL to set the origin.
Parameters | |
---|---|
data |
String: a String of data in the given encoding This value cannot be null . |
mimeType |
String?: the MIME type of the data, e.g. 'text/html'. This value may be null . |
encoding |
String?: the encoding of the data This value may be null . |
loadDataWithBaseURL
open fun loadDataWithBaseURL(
baseUrl: String?,
data: String,
mimeType: String?,
encoding: String?,
historyUrl: String?
): Unit
Loads the given data into this 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.
The mimeType
parameter specifies the format of the data. If WebView can't handle the specified MIME type, it will download the data. If null
, defaults to 'text/html'.
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, and the data will be treated as part of a data: URL, including the requirement that the content be URL-encoded or base64 encoded. If the base URL uses any other scheme, then the data will be loaded into the WebView as a plain string (i.e. not part of a data URL) and any URL-encoded entities in the string will not be decoded.
Note that the baseUrl is sent in the 'Referer' HTTP header when requesting subresources (images, etc.) of the page loaded using this method.
If a valid HTTP or HTTPS base URL is not specified in baseUrl
, then content loaded using this method will have a window.origin
value of "null"
. This must not be considered to be a trusted origin by the application or by any JavaScript code running inside the WebView (for example, event sources in DOM event handlers or web messages), because malicious content can also create frames with a null origin. If you need to identify the main frame's origin in a trustworthy way, you should use a valid HTTP or HTTPS base URL to set the origin.
Parameters | |
---|---|
baseUrl |
String?: the URL to use as the page's base URL. If null defaults to 'about:blank'. |
data |
String: a String of data in the given encoding This value cannot be null . |
mimeType |
String?: the MIME type of the data, e.g. 'text/html'. This value may be null . |
encoding |
String?: the encoding of the data This value may be null . |
historyUrl |
String?: the URL to use as the history entry. If null defaults to 'about:blank'. If non-null, this must be a valid URL. |
loadUrl
open fun loadUrl(
url: String,
additionalHttpHeaders: MutableMap<String!, String!>
): Unit
Loads the given URL with additional HTTP headers, specified as a map from name to value. Note that if this map contains any of the headers that are set by default by this WebView, such as those controlling caching, accept types or the User-Agent, their values may be overridden by this WebView's defaults.
Some older WebView implementations require additionalHttpHeaders
to be mutable.
Also see compatibility note on evaluateJavascript
.
Parameters | |
---|---|
url |
String: the URL of the resource to load This value cannot be null . |
additionalHttpHeaders |
MutableMap<String!, String!>: map with additional headers This value cannot be null . |
loadUrl
open fun loadUrl(url: String): Unit
Loads the given URL.
Also see compatibility note on evaluateJavascript
.
Parameters | |
---|---|
url |
String: the URL of the resource to load This value cannot be null . |
onApplyWindowInsets
open fun onApplyWindowInsets(insets: WindowInsets!): WindowInsets!
Parameters | |
---|---|
insets |
WindowInsets!: Insets to apply |
Return | |
---|---|
WindowInsets! |
The supplied insets with any applied insets consumed |
onCheckIsTextEditor
open fun onCheckIsTextEditor(): Boolean
Return | |
---|---|
Boolean |
Returns true if this view is a text editor, else false. |
onChildViewAdded
open funonChildViewAdded(
parent: View!,
child: View!
): Unit
Deprecated: WebView no longer needs to implement ViewGroup.OnHierarchyChangeListener. This method does nothing now.
Parameters | |
---|---|
parent |
View!: the view in which a child was added |
child |
View!: the new child view added in the hierarchy |
onChildViewRemoved
open funonChildViewRemoved(
p: View!,
child: View!
): Unit
Deprecated: WebView no longer needs to implement ViewGroup.OnHierarchyChangeListener. This method does nothing now.
Parameters | |
---|---|
parent |
the view from which the child was removed |
child |
View!: the child removed from the hierarchy |
onCreateInputConnection
open fun onCreateInputConnection(outAttrs: EditorInfo!): InputConnection!
Creates a new InputConnection for an InputMethod to interact with the WebView. This is similar to View#onCreateInputConnection
but note that WebView calls InputConnection methods on a thread other than the UI thread. If these methods are overridden, then the overriding methods should respect thread restrictions when calling View methods or accessing data.
Parameters | |
---|---|
outAttrs |
EditorInfo!: Fill in with attribute information about the connection. |
onCreateVirtualViewTranslationRequests
open fun onCreateVirtualViewTranslationRequests(
virtualIds: LongArray,
supportedFormats: IntArray,
requestsCollector: Consumer<ViewTranslationRequest!>
): Unit
Collects ViewTranslationRequest
s which represents the content to be translated for the virtual views in the host view. This is called if this view returned a virtual view structure from onProvideContentCaptureStructure
and the system determined that those virtual views were relevant for translation.
The default implementation does nothing.
Parameters | |
---|---|
virtualIds |
LongArray: This value cannot be null . |
supportedFormats |
IntArray: This value cannot be null . Value is android.view.translation.TranslationSpec#DATA_FORMAT_TEXT |
requestsCollector |
Consumer<ViewTranslationRequest!>: This value cannot be null . |
Return | |
---|---|
Unit |
This value may be null . |
onDragEvent
open fun onDragEvent(event: DragEvent!): Boolean
Parameters | |
---|---|
event |
DragEvent!: The DragEvent object sent by the system. The DragEvent#getAction() method returns an action type constant that indicates the type of drag event represented by this object. |
Return | |
---|---|
Boolean |
true if the method successfully handled the drag event, otherwise false .
The method must return The method should return For all other events, the return value is |
onGenericMotionEvent
open fun onGenericMotionEvent(event: MotionEvent!): Boolean
Parameters | |
---|---|
event |
MotionEvent!: The generic motion event being processed. |
Return | |
---|---|
Boolean |
True if the event was handled, false otherwise. |
onGlobalFocusChanged
open funonGlobalFocusChanged(
oldFocus: View!,
newFocus: View!
): Unit
Deprecated: WebView should not have implemented ViewTreeObserver.OnGlobalFocusChangeListener. This method does nothing now.
Parameters | |
---|---|
oldFocus |
View!: The previously focused view, if any. |
newFocus |
View!: The newly focused View, if any. |
onHoverEvent
open fun onHoverEvent(event: MotionEvent!): Boolean
Parameters | |
---|---|
event |
MotionEvent!: The motion event that describes the hover. |
Return | |
---|---|
Boolean |
True if the view handled the hover event. |
onKeyDown
open fun onKeyDown(
keyCode: Int,
event: KeyEvent!
): Boolean
Parameters | |
---|---|
keyCode |
Int: a key code that represents the button pressed, from android.view.KeyEvent |
event |
KeyEvent!: the KeyEvent object that defines the button action |
Return | |
---|---|
Boolean |
If you handled the event, return true. If you want to allow the event to be handled by the next receiver, return false. |
onKeyMultiple
open fun onKeyMultiple(
keyCode: Int,
repeatCount: Int,
event: KeyEvent!
): Boolean
Parameters | |
---|---|
keyCode |
Int: A key code that represents the button pressed, from android.view.KeyEvent . |
count |
Number of pairs as returned by event.getRepeatCount(). |
event |
KeyEvent!: The KeyEvent object that defines the button action. |
repeatCount |
Int: The number of times the action was made. |
Return | |
---|---|
Boolean |
If you handled the event, return true. If you want to allow the event to be handled by the next receiver, return false. |
onKeyUp
open fun onKeyUp(
keyCode: Int,
event: KeyEvent!
): Boolean
Parameters | |
---|---|
keyCode |
Int: A key code that represents the button pressed, from android.view.KeyEvent . |
event |
KeyEvent!: The KeyEvent object that defines the button action. |
Return | |
---|---|
Boolean |
If you handled the event, return true. If you want to allow the event to be handled by the next receiver, return false. |
onPause
open fun onPause(): Unit
Does a best-effort attempt to pause any processing that can be paused safely, such as animations and geolocation. Note that this call does not pause JavaScript. To pause JavaScript globally, use pauseTimers
. To resume WebView, call onResume
.
onProvideAutofillVirtualStructure
open fun onProvideAutofillVirtualStructure(
structure: ViewStructure!,
flags: Int
): Unit
Populates a ViewStructure
containing virtual children to fullfil an autofill request.
This method should be used when the view manages a virtual structure under this view. For example, a view that draws input fields using draw(android.graphics.Canvas)
.
When implementing this method, subclasses must follow the rules below:
- Add virtual children by calling the
ViewStructure#newChild(int)
orViewStructure#asyncNewChild(int)
methods, where theid
is an unique id identifying the children in the virtual structure. - The children hierarchy can have multiple levels if necessary, but ideally it should exclude intermediate levels that are irrelevant for autofill; that would improve the autofill performance.
- Also implement
autofill(android.util.SparseArray)
to autofill the virtual children. - Set the autofill properties of the child structure as defined by
onProvideAutofillStructure(android.view.ViewStructure,int)
, usingViewStructure#setAutofillId(AutofillId, int)
to set its autofill id. - Call
android.view.autofill.AutofillManager#notifyViewEntered(View, int, Rect)
and/orandroid.view.autofill.AutofillManager#notifyViewExited(View, int)
when the focused virtual child changed. - Override
isVisibleToUserForAutofill(int)
to allow the platform to query whether a given virtual view is visible to the user in order to support triggering save when all views of interest go away. - Call
android.view.autofill.AutofillManager#notifyValueChanged(View, int, AutofillValue)
when the value of a virtual child changed. - Call
android.view.autofill.AutofillManager#notifyViewVisibilityChanged(View, int, boolean)
when the visibility of a virtual child changed. - Call
android.view.autofill.AutofillManager#notifyViewClicked(View, int)
when a virtual child is clicked. - Call
AutofillManager#commit()
when the autofill context of the view structure changed and the current context should be committed (for example, when the user tapped aSUBMIT
button in an HTML page). - Call
AutofillManager#cancel()
when the autofill context of the view structure changed and the current context should be canceled (for example, when the user tapped aCANCEL
button in an HTML page). - Provide ways for users to manually request autofill by calling
AutofillManager#requestAutofill(View, int, Rect)
. - The
left
andtop
values set inViewStructure#setDimens(int, int, int, int, int, int)
must be relative to the nextViewGroup#isImportantForAutofill()
predecessor view included in the structure.
Views with virtual children support the Autofill Framework mainly by:
- Providing the metadata defining what the virtual children mean and how they can be autofilled.
- Implementing the methods that autofill the virtual children.
This method is responsible for the former; autofill(android.util.SparseArray)
is responsible for the latter.
The ViewStructure
traditionally represents a View
, while for web pages it represent HTML nodes. Hence, it's necessary to "map" the HTML properties in a way that is understood by the android.service.autofill.AutofillService
implementations:
- Only the HTML nodes inside a
FORM
are generated. - The source of the HTML is set using
ViewStructure#setWebDomain(String)
in the node representing the WebView. - If a web page has multiple
FORM
s, only the data for the current form is represented—if the user taps a field from another form, then the current autofill context is canceled (by callingandroid.view.autofill.AutofillManager#cancel()
and a new context is created for thatFORM
. - Similarly, if the page has
IFRAME
nodes, they are not initially represented in the view structure until the user taps a field from aFORM
inside theIFRAME
, in which case it would be treated the same way as multiple forms described above, except that theweb domain
of theFORM
contains thesrc
attribute from theIFRAME
node. - The W3C autofill field (
autocomplete
tag attribute) maps toViewStructure#setAutofillHints(String[])
. - If the view is editable, the
ViewStructure#setAutofillType(int)
andViewStructure#setAutofillValue(AutofillValue)
must be set. - The
placeholder
attribute maps toViewStructure#setHint(CharSequence)
. - Other HTML attributes can be represented through
ViewStructure#setHtmlInfo(android.view.ViewStructure.HtmlInfo)
.
If the WebView implementation can determine that the value of a field was set statically (for example, not through Javascript), it should also call structure.setDataIsSensitive(false)
.
For example, an HTML form with 2 fields for username and password:
<label>Username:</label> <input type="text" name="username" id="user" value="Type your username" autocomplete="username" placeholder="Email or username"> <label>Password:</label> <input type="password" name="password" id="pass" autocomplete="current-password" placeholder="Password">
Would map to:
int index = structure.addChildCount(2); ViewStructure username = structure.newChild(index); username.setAutofillId(structure.getAutofillId(), 1); // id 1 - first child username.setAutofillHints("username"); username.setHtmlInfo(username.newHtmlInfoBuilder("input") .addAttribute("type", "text") .addAttribute("name", "username") .addAttribute("label", "Username:") .build()); username.setHint("Email or username"); username.setAutofillType(View.AUTOFILL_TYPE_TEXT); username.setAutofillValue(AutofillValue.forText("Type your username")); // Value of the field is not sensitive because it was created statically and not changed. username.setDataIsSensitive(false); ViewStructure password = structure.newChild(index + 1); username.setAutofillId(structure, 2); // id 2 - second child password.setAutofillHints("current-password"); password.setHtmlInfo(password.newHtmlInfoBuilder("input") .addAttribute("type", "password") .addAttribute("name", "password") .addAttribute("label", "Password:") .build()); password.setHint("Password"); password.setAutofillType(View.AUTOFILL_TYPE_TEXT);
Parameters | |
---|---|
structure |
ViewStructure!: fill in with virtual children data for autofill purposes. |
flags |
Int: optional flags. |
onProvideContentCaptureStructure
open fun onProvideContentCaptureStructure(
structure: ViewStructure,
flags: Int
): Unit
Populates a ViewStructure
for content capture.
This method is called after a view that is eligible for content capture (for example, if it isImportantForContentCapture()
, an intelligence service is enabled for the user, and the activity rendering the view is enabled for content capture) is laid out and is visible. The populated structure is then passed to the service through ContentCaptureSession#notifyViewAppeared(ViewStructure)
.
The default implementation of this method sets the most relevant properties based on related View
methods, and views in the standard Android widgets library also override it to set their relevant properties. Therefore, if overriding this method, it is recommended to call super.onProvideContentCaptureStructure()
.
Note: views that manage a virtual structure under this view must populate just the node representing this view and return right away, then asynchronously report (not necessarily in the UI thread) when the children nodes appear, disappear or have their text changed by calling ContentCaptureSession#notifyViewAppeared(ViewStructure)
, ContentCaptureSession#notifyViewDisappeared(AutofillId)
, and ContentCaptureSession#notifyViewTextChanged(AutofillId, CharSequence)
respectively. The structure for a child must be created using ContentCaptureSession#newVirtualViewStructure(AutofillId, long)
, and the autofillId
for a child can be obtained either through childStructure.getAutofillId()
or ContentCaptureSession#newAutofillId(AutofillId, long)
.
When the virtual view hierarchy represents a web page, you should also:
- Call
ContentCaptureManager#getContentCaptureConditions()
to infer content capture events should be generate for that URL. - Create a new
ContentCaptureSession
child for every HTML element that renders a new URL (like anIFRAME
) and use that session to notify events from that subtree.
Note: the following methods of the structure
will be ignored:
ViewStructure#setChildCount(int)
ViewStructure#addChildCount(int)
ViewStructure#getChildCount()
ViewStructure#newChild(int)
ViewStructure#asyncNewChild(int)
ViewStructure#asyncCommit()
ViewStructure#setWebDomain(String)
ViewStructure#newHtmlInfoBuilder(String)
ViewStructure#setHtmlInfo(android.view.ViewStructure.HtmlInfo)
ViewStructure#setDataIsSensitive(boolean)
ViewStructure#setAlpha(float)
ViewStructure#setElevation(float)
ViewStructure#setTransformation(Matrix)
Parameters | |
---|---|
structure |
ViewStructure: This value cannot be null . |
onProvideVirtualStructure
open fun onProvideVirtualStructure(structure: ViewStructure!): Unit
onResolvePointerIcon
open fun onResolvePointerIcon(
event: MotionEvent,
pointerIndex: Int
): PointerIcon?
Resolve the pointer icon that should be used for specified pointer in the motion event. The default implementation will resolve the pointer icon to one set using setPointerIcon(android.view.PointerIcon)
for mouse devices. Subclasses may override this to customize the icon for the given pointer. For example, the pointer icon for a stylus pointer can be resolved in the following way:
@Override
public PointerIcon onResolvePointerIcon(MotionEvent event, int pointerIndex) {
final int toolType = event.getToolType(pointerIndex);
if (!event.isFromSource(InputDevice.SOURCE_MOUSE)
&& event.isFromSource(InputDevice.SOURCE_STYLUS)
&& (toolType == MotionEvent.TOOL_TYPE_STYLUS
|| toolType == MotionEvent.TOOL_TYPE_ERASER)) {
// Show this pointer icon only if this pointer is a stylus.
return PointerIcon.getSystemIcon(mContext, PointerIcon.TYPE_WAIT);
}
// Use the default logic for determining the pointer icon for other non-stylus pointers,
// like for the mouse cursor.
return super.onResolvePointerIcon(event, pointerIndex);
}
Parameters | |
---|---|
event |
MotionEvent: This value cannot be null . |
pointerIndex |
Int: The index of the pointer in event for which to retrieve the PointerIcon . This will be between 0 and MotionEvent#getPointerCount() . |
Return | |
---|---|
PointerIcon? |
This value may be null . |
onResume
open fun onResume(): Unit
Resumes a WebView after a previous call to onPause
.
onTouchEvent
open fun onTouchEvent(event: MotionEvent!): Boolean
Parameters | |
---|---|
event |
MotionEvent!: The motion event. |
Return | |
---|---|
Boolean |
True if the event was handled, false otherwise. |
onTrackballEvent
open fun onTrackballEvent(event: MotionEvent!): Boolean
Parameters | |
---|---|
event |
MotionEvent!: The motion event. |
Return | |
---|---|
Boolean |
True if the event was handled, false otherwise. |
onVirtualViewTranslationResponses
open fun onVirtualViewTranslationResponses(response: LongSparseArray<ViewTranslationResponse!>): Unit
Called when the content from View#onCreateVirtualViewTranslationRequests
had been translated by the TranslationService.
The default implementation does nothing.
Parameters | |
---|---|
response |
LongSparseArray<ViewTranslationResponse!>: This value cannot be null . |
onWindowFocusChanged
open fun onWindowFocusChanged(hasWindowFocus: Boolean): Unit
Parameters | |
---|---|
hasWindowFocus |
Boolean: True if the window containing this view now has focus, false otherwise. |
overlayHorizontalScrollbar
open funoverlayHorizontalScrollbar(): Boolean
Deprecated: This method is now obsolete.
Gets whether horizontal scrollbar has overlay style.
Return | |
---|---|
Boolean |
true |
overlayVerticalScrollbar
open funoverlayVerticalScrollbar(): Boolean
Deprecated: This method is now obsolete.
Gets whether vertical scrollbar has overlay style.
Return | |
---|---|
Boolean |
false |
pageDown
open fun pageDown(bottom: Boolean): Boolean
Scrolls the contents of this WebView down by half the page size.
Parameters | |
---|---|
bottom |
Boolean: true to jump to bottom of page |
Return | |
---|---|
Boolean |
true if the page was scrolled |
pageUp
open fun pageUp(top: Boolean): Boolean
Scrolls the contents of this WebView up by half the view size.
Parameters | |
---|---|
top |
Boolean: true to jump to the top of the page |
Return | |
---|---|
Boolean |
true if the page was scrolled |
pauseTimers
open fun pauseTimers(): Unit
Pauses 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.
performLongClick
open fun performLongClick(): Boolean
Return | |
---|---|
Boolean |
true if one of the above receivers consumed the event, false otherwise |
postUrl
open fun postUrl(
url: String,
postData: ByteArray
): Unit
Loads the URL with postData using "POST" method into this WebView. If url is not a network URL, it will be loaded with loadUrl(java.lang.String)
instead, ignoring the postData param.
Parameters | |
---|---|
url |
String: the URL of the resource to load This value cannot be null . |
postData |
ByteArray: the data will be passed to "POST" request, which must be be "application/x-www-form-urlencoded" encoded. This value cannot be null . |
postVisualStateCallback
open fun postVisualStateCallback(
requestId: Long,
callback: WebView.VisualStateCallback
): Unit
Posts a VisualStateCallback
, which will be called when the current state of the WebView is ready to be drawn.
Because updates to the DOM are processed asynchronously, updates to the DOM may not immediately be reflected visually by subsequent WebView#onDraw
invocations. The VisualStateCallback
provides a mechanism to notify the caller when the contents of the DOM at the current time are ready to be drawn the next time the WebView
draws.
The next draw after the callback completes is guaranteed to reflect all the updates to the DOM up to the point at which the VisualStateCallback
was posted, but it may also contain updates applied after the callback was posted.
The state of the DOM covered by this API includes the following:
- primitive HTML elements (div, img, span, etc..)
- images
- CSS animations
- WebGL
- canvas
- the video tag
To guarantee that the WebView
will successfully render the first frame after the VisualStateCallback#onComplete
method has been called a set of conditions must be met:
- If the
WebView
's visibility is set toVISIBLE
then theWebView
must be attached to the view hierarchy. - If the
WebView
's visibility is set toINVISIBLE
then theWebView
must be attached to the view hierarchy and must be madeVISIBLE
from theVisualStateCallback#onComplete
method. - If the
WebView
's visibility is set toGONE
then theWebView
must be attached to the view hierarchy and itsLayoutParams
's width and height need to be set to fixed values and must be madeVISIBLE
from theVisualStateCallback#onComplete
method.
When using this API it is also recommended to enable pre-rasterization if the WebView
is off screen to avoid flickering. See WebSettings#setOffscreenPreRaster
for more details and do consider its caveats.
Parameters | |
---|---|
requestId |
Long: An id that will be returned in the callback to allow callers to match requests with callbacks. |
callback |
WebView.VisualStateCallback: The callback to be invoked. This value cannot be null . |
postWebMessage
open fun postWebMessage(
message: WebMessage,
targetOrigin: Uri
): Unit
Post a message to main frame. The embedded application can restrict the messages to a certain target origin. See HTML5 spec for how target origin can be used.
A target origin can be set as a wildcard ("*"). However this is not recommended. See the page above for security issues.
Content loaded via loadData(java.lang.String,java.lang.String,java.lang.String)
will not have a valid origin, and thus cannot be sent messages securely. If you need to send messages using this function, you should use loadDataWithBaseURL(java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String)
with a valid HTTP or HTTPS baseUrl
to define a valid origin that can be used for messaging.
Parameters | |
---|---|
message |
WebMessage: the WebMessage This value cannot be null . |
targetOrigin |
Uri: the target origin. This value cannot be null . |
removeJavascriptInterface
open fun removeJavascriptInterface(name: String): Unit
Removes a previously injected Java object from this WebView. Note that the removal will not be reflected in JavaScript until the page is next (re)loaded. See addJavascriptInterface
.
Parameters | |
---|---|
name |
String: the name used to expose the object in JavaScript This value cannot be null . |
requestChildRectangleOnScreen
open fun requestChildRectangleOnScreen(
child: View,
rect: Rect!,
immediate: Boolean
): Boolean
Parameters | |
---|---|
child |
View: The direct child making the request. This value cannot be null . |
rectangle |
The rectangle in the child's coordinates the child wishes to be on the screen. |
immediate |
Boolean: True to forbid animated or delayed scrolling, false otherwise |
Return | |
---|---|
Boolean |
Whether the group scrolled to handle the operation |
requestFocus
open fun requestFocus(
direction: Int,
previouslyFocusedRect: Rect!
): Boolean
Parameters | |
---|---|
direction |
Int: One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT |
previouslyFocusedRect |
Rect!: 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. |
Return | |
---|---|
Boolean |
Whether this view or one of its descendants actually took focus. |
requestFocusNodeHref
open fun requestFocusNodeHref(hrefMsg: Message?): Unit
Requests 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 |
Message?: the message to 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. This value may be null . |
requestImageRef
open fun requestImageRef(msg: Message): Unit
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.
Parameters | |
---|---|
msg |
Message: the message to be dispatched with the result of the request as the data member with "url" as key. The result can be null . |
restoreState
open fun restoreState(inState: Bundle): WebBackForwardList?
Restores the state of this WebView from the given Bundle. This method is intended for use in android.app.Activity#onRestoreInstanceState and should be called to restore the state of this WebView. If it is called after this 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.
Parameters | |
---|---|
inState |
Bundle: the incoming Bundle of state This value cannot be null . |
Return | |
---|---|
WebBackForwardList? |
the restored back/forward list or null if restoreState failed |
resumeTimers
open fun resumeTimers(): Unit
Resumes all layout, parsing, and JavaScript timers for all WebViews. This will resume dispatching all timers.
savePassword
open funsavePassword(
host: String!,
username: String!,
password: String!
): Unit
Deprecated: Saving passwords in WebView will not be supported in future versions.
Sets a username and password pair for the specified host. This data is used by the WebView to autocomplete username and password fields in web forms. Note that this is unrelated to the credentials used for HTTP authentication.
Parameters | |
---|---|
host |
String!: the host that required the credentials |
username |
String!: the username for the given host |
password |
String!: the password for the given host |
saveState
open fun saveState(outState: Bundle): WebBackForwardList?
Saves the state of this WebView used in android.app.Activity#onSaveInstanceState. Please note that this method no longer stores the display data for this WebView. The previous behavior could potentially leak files if restoreState
was never called.
Parameters | |
---|---|
outState |
Bundle: the Bundle to store this WebView's state This value cannot be null . |
Return | |
---|---|
WebBackForwardList? |
the same copy of the back/forward list used to save the state, null if the method fails. |
saveWebArchive
open fun saveWebArchive(filename: String): Unit
Saves the current view as a web archive.
Parameters | |
---|---|
filename |
String: the filename where the archive should be placed This value cannot be null . |
saveWebArchive
open fun saveWebArchive(
basename: String,
autoname: Boolean,
callback: ValueCallback<String!>?
): Unit
Saves the current view as a web archive.
Parameters | |
---|---|
basename |
String: the filename where the archive should be placed This value cannot be null . |
autoname |
Boolean: 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 |
ValueCallback<String!>?: 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. |
setBackgroundColor
open fun setBackgroundColor(color: Int): Unit
Parameters | |
---|---|
color |
Int: the color of the background |
setCertificate
open funsetCertificate(certificate: SslCertificate!): Unit
Deprecated: Calling this function has no useful effect, and will be ignored in future releases.
Sets the SSL certificate for the main top-level page.
setDataDirectorySuffix
open static fun setDataDirectorySuffix(suffix: String): Unit
Define the directory used to store WebView data for the current process. The provided suffix will be used when constructing data and cache directory paths. If this API is not called, no suffix will be used. Each directory can be used by only one process in the application. If more than one process in an app wishes to use WebView, only one process can use the default directory, and other processes must call this API to define a unique suffix.
This means that different processes in the same application cannot directly share WebView-related data, since the data directories must be distinct. Applications that use this API may have to explicitly pass data between processes. For example, login cookies may have to be copied from one process's cookie jar to the other using CookieManager
if both processes' WebViews are intended to be logged in.
Most applications should simply ensure that all components of the app that rely on WebView are in the same process, to avoid needing multiple data directories. The disableWebView
method can be used to ensure that the other processes do not use WebView by accident in this case.
This API must be called before any instances of WebView are created in this process and before any other methods in the android.webkit package are called by this process.
Parameters | |
---|---|
suffix |
String: The directory name suffix to be used for the current process. Must not contain a path separator. This value cannot be null . |
Exceptions | |
---|---|
java.lang.IllegalStateException |
if WebView has already been initialized in the current process. |
java.lang.IllegalArgumentException |
if the suffix contains a path separator. |
setDownloadListener
open fun setDownloadListener(listener: DownloadListener?): Unit
Registers 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 |
DownloadListener?: an implementation of DownloadListener This value may be null . |
setFindListener
open fun setFindListener(listener: WebView.FindListener?): Unit
Registers the listener to be notified as find-on-page operations progress. This will replace the current listener.
Parameters | |
---|---|
listener |
WebView.FindListener?: an implementation of FindListener This value may be null . |
setHorizontalScrollbarOverlay
open funsetHorizontalScrollbarOverlay(overlay: Boolean): Unit
Deprecated: This method has no effect.
Specifies whether the horizontal scrollbar has overlay style.
Parameters | |
---|---|
overlay |
Boolean: true if horizontal scrollbar should have overlay style |
setHttpAuthUsernamePassword
open funsetHttpAuthUsernamePassword(
host: String!,
realm: String!,
username: String!,
password: String!
): Unit
Deprecated: Use WebViewDatabase#setHttpAuthUsernamePassword
instead
Stores HTTP authentication credentials for a given host and realm to the WebViewDatabase
instance.
Parameters | |
---|---|
host |
String!: the host to which the credentials apply |
realm |
String!: the realm to which the credentials apply |
username |
String!: the username |
password |
String!: the password |
setInitialScale
open fun setInitialScale(scaleInPercent: Int): Unit
Sets the initial scale for this WebView. 0 means default. The behavior for the default scale depends on the state of WebSettings#getUseWideViewPort()
and WebSettings#getLoadWithOverviewMode()
. If the content fits into the WebView control by width, then the zoom is set to 100%. For wide content, the behavior depends on the state of WebSettings#getLoadWithOverviewMode()
. If its value is true
, the content will be zoomed out to be fit by width into the WebView control, otherwise not. If initial scale is greater than 0, WebView starts with this value as initial scale. Please note that unlike the scale properties in the viewport meta tag, this method doesn't take the screen density into account.
Parameters | |
---|---|
scaleInPercent |
Int: the initial scale in percent |
setLayerType
open fun setLayerType(
layerType: Int,
paint: Paint?
): Unit
Parameters | |
---|---|
layerType |
Int: The type of layer to use with this view, must be one of LAYER_TYPE_NONE , LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE Value is android.view.View#LAYER_TYPE_NONE , android.view.View#LAYER_TYPE_SOFTWARE , or android.view.View#LAYER_TYPE_HARDWARE |
paint |
Paint?: The paint used to compose the layer. This argument is optional and can be null. It is ignored when the layer type is LAYER_TYPE_NONE |
setLayoutParams
open fun setLayoutParams(params: ViewGroup.LayoutParams!): Unit
Parameters | |
---|---|
params |
ViewGroup.LayoutParams!: The layout parameters for this view, cannot be null |
setMapTrackballToArrowKeys
open funsetMapTrackballToArrowKeys(setMap: Boolean): Unit
Deprecated: Only the default case, true
, will be supported in a future version.
setNetworkAvailable
open fun setNetworkAvailable(networkUp: Boolean): Unit
Informs 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: a boolean indicating if network is available |
setOverScrollMode
open fun setOverScrollMode(mode: Int): Unit
Parameters | |
---|---|
overScrollMode |
The new over-scroll mode for this view. |
setPictureListener
open funsetPictureListener(listener: WebView.PictureListener!): Unit
Deprecated: This method is now obsolete.
Sets the Picture listener. This is an interface used to receive notifications of a new Picture.
Parameters | |
---|---|
listener |
WebView.PictureListener!: an implementation of WebView.PictureListener |
setRendererPriorityPolicy
open fun setRendererPriorityPolicy(
rendererRequestedPriority: Int,
waivedWhenNotVisible: Boolean
): Unit
Set the renderer priority policy for this WebView
. The priority policy will be used to determine whether an out of process renderer should be considered to be a target for OOM killing. Because a renderer can be associated with more than one WebView, the final priority it is computed as the maximum of any attached WebViews. When a WebView is destroyed it will cease to be considerered when calculating the renderer priority. Once no WebViews remain associated with the renderer, the priority of the renderer will be reduced to RENDERER_PRIORITY_WAIVED
. The default policy is to set the priority to RENDERER_PRIORITY_IMPORTANT
regardless of visibility, and this should not be changed unless the caller also handles renderer crashes with WebViewClient#onRenderProcessGone
. Any other setting will result in WebView renderers being killed by the system more aggressively than the application.
Parameters | |
---|---|
rendererRequestedPriority |
Int: the minimum priority at which this WebView desires the renderer process to be bound. Value is android.webkit.WebView#RENDERER_PRIORITY_WAIVED , android.webkit.WebView#RENDERER_PRIORITY_BOUND , or android.webkit.WebView#RENDERER_PRIORITY_IMPORTANT |
waivedWhenNotVisible |
Boolean: if true , this flag specifies that when this WebView is not visible, it will be treated as if it had requested a priority of RENDERER_PRIORITY_WAIVED . |
setSafeBrowsingWhitelist
open static fun setSafeBrowsingWhitelist(
hosts: MutableList<String!>,
callback: ValueCallback<Boolean!>?
): Unit
Sets the list of hosts (domain names/IP addresses) that are exempt from SafeBrowsing checks. The list is global for all the WebViews.
Each rule should take one of these:
Rule | Example | Matches Subdomain |
---|---|---|
HOSTNAME | example.com | Yes |
.HOSTNAME | .example.com | No |
IPV4_LITERAL | 192.168.1.1 | No |
IPV6_LITERAL_WITH_BRACKETS | [10:20:30:40:50:60:70:80] | No |
All other rules, including wildcards, are invalid.
The correct syntax for hosts is defined by RFC 3986.
Parameters | |
---|---|
hosts |
MutableList<String!>: the list of hosts This value cannot be null . |
callback |
ValueCallback<Boolean!>?: will be called with true if hosts are successfully added to the allowlist. It will be called with false if any hosts are malformed. The callback will be run on the UI thread This value may be null . |
setScrollBarStyle
open fun setScrollBarStyle(style: Int): Unit
Parameters | |
---|---|
style |
Int: the style of the scrollbars. Should be one of SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. Value is android.view.View#SCROLLBARS_INSIDE_OVERLAY , android.view.View#SCROLLBARS_INSIDE_INSET , android.view.View#SCROLLBARS_OUTSIDE_OVERLAY , or android.view.View#SCROLLBARS_OUTSIDE_INSET |
setTextClassifier
open fun setTextClassifier(textClassifier: TextClassifier?): Unit
Sets the TextClassifier
for this WebView.
Parameters | |
---|---|
textClassifier |
TextClassifier?: This value may be null . |
setVerticalScrollbarOverlay
open funsetVerticalScrollbarOverlay(overlay: Boolean): Unit
Deprecated: This method has no effect.
Specifies whether the vertical scrollbar has overlay style.
Parameters | |
---|---|
overlay |
Boolean: true if vertical scrollbar should have overlay style |
setWebChromeClient
open fun setWebChromeClient(client: WebChromeClient?): Unit
Sets 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 |
WebChromeClient?: an implementation of WebChromeClient This value may be null . |
See Also
setWebContentsDebuggingEnabled
open static fun setWebContentsDebuggingEnabled(enabled: Boolean): Unit
Enables debugging of web contents (HTML / CSS / JavaScript) loaded into any WebViews of this application. This flag can be enabled in order to facilitate debugging of web layouts and JavaScript code running inside WebViews. Please refer to WebView documentation for the debugging guide.
In WebView 113.0.5656.0 and later, this is enabled automatically if the app is declared as android:debuggable="true"
in its manifest; otherwise, the default is false
.
Enabling web contents debugging allows the state of any WebView in the app to be inspected and modified by the user via adb. This is a security liability and should not be enabled in production builds of apps unless this is an explicitly intended use of the app. More info on secure debug settings.
Parameters | |
---|---|
enabled |
Boolean: whether to enable web contents debugging |
setWebViewClient
open fun setWebViewClient(client: WebViewClient): Unit
Sets the WebViewClient that will receive various notifications and requests. This will replace the current handler.
Parameters | |
---|---|
client |
WebViewClient: an implementation of WebViewClient This value cannot be null . |
See Also
setWebViewRenderProcessClient
open fun setWebViewRenderProcessClient(
executor: Executor,
webViewRenderProcessClient: WebViewRenderProcessClient
): Unit
Sets the renderer client object associated with this WebView.
The renderer client encapsulates callbacks relevant to WebView renderer state. See WebViewRenderProcessClient
for details.
Although many WebView instances may share a single underlying renderer, and renderers may live either in the application process, or in a sandboxed process that is isolated from the application process, instances of WebViewRenderProcessClient
are set per-WebView. Callbacks represent renderer events from the perspective of this WebView, and may or may not be correlated with renderer events affecting other WebViews.
Parameters | |
---|---|
executor |
Executor: the Executor on which WebViewRenderProcessClient callbacks will execute. This value cannot be null . Callback and listener events are dispatched through this Executor , providing an easy way to control which thread is used. To dispatch events through the main thread of your application, you can use Context.getMainExecutor() . Otherwise, provide an Executor that dispatches to an appropriate thread. |
webViewRenderProcessClient |
WebViewRenderProcessClient: the WebViewRenderProcessClient object. This value cannot be null . |
setWebViewRenderProcessClient
open fun setWebViewRenderProcessClient(webViewRenderProcessClient: WebViewRenderProcessClient?): Unit
Sets the renderer client object associated with this WebView. See setWebViewRenderProcessClient(java.util.concurrent.Executor,android.webkit.WebViewRenderProcessClient)
for details.
WebViewRenderProcessClient
callbacks will run on the thread that this WebView was initialized on.
Parameters | |
---|---|
webViewRenderProcessClient |
WebViewRenderProcessClient?: the WebViewRenderProcessClient object. This value may be null . |
shouldDelayChildPressedState
open funshouldDelayChildPressedState(): Boolean
Deprecated: Deprecated in Java.
showFindDialog
open funshowFindDialog(
text: String?,
showIme: Boolean
): Boolean
Deprecated: This method does not work reliably on all Android versions; implementing a custom find dialog using WebView.findAllAsync() provides a more robust solution.
Starts an ActionMode for finding text in this WebView. Only works if this WebView is attached to the view system.
Parameters | |
---|---|
text |
String?: 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 |
Boolean: if true , show the IME, assuming the user will begin typing. If false and text is non-null, perform a find all. |
Return | |
---|---|
Boolean |
true if the find dialog is shown, false otherwise |
startSafeBrowsing
open static fun startSafeBrowsing(
context: Context,
callback: ValueCallback<Boolean!>?
): Unit
Starts Safe Browsing initialization.
URL loads are not guaranteed to be protected by Safe Browsing until after callback
is invoked with true
. Safe Browsing is not fully supported on all devices. For those devices callback
will receive false
.
This should not be called if Safe Browsing has been disabled by manifest tag or android.webkit.WebSettings#setSafeBrowsingEnabled
. This prepares resources used for Safe Browsing.
This should be called with the Application Context (and will always use the Application context to do its work regardless).
Parameters | |
---|---|
context |
Context: Application Context. This value cannot be null . |
callback |
ValueCallback<Boolean!>?: will be called on the UI thread with true if initialization is successful, false otherwise. This value may be null . |
zoomBy
open fun zoomBy(zoomFactor: Float): Unit
Performs a zoom operation in this WebView.
Parameters | |
---|---|
zoomFactor |
Float: the zoom factor to apply. The zoom factor will be clamped to the WebView's zoom limits. This value must be in the range 0.01 to 100.0 inclusive. |
zoomIn
open fun zoomIn(): Boolean
Performs zoom in in this WebView.
Return | |
---|---|
Boolean |
true if zoom in succeeds, false if no zoom changes |
zoomOut
open fun zoomOut(): Boolean
Performs zoom out in this WebView.
Return | |
---|---|
Boolean |
true if zoom out succeeds, false if no zoom changes |
Protected methods
computeHorizontalScrollOffset
protected open fun computeHorizontalScrollOffset(): Int
Return | |
---|---|
Int |
the horizontal offset of the scrollbar's thumb |
computeHorizontalScrollRange
protected open fun computeHorizontalScrollRange(): Int
Return | |
---|---|
Int |
the total horizontal range represented by the horizontal scrollbar |
computeVerticalScrollExtent
protected open fun computeVerticalScrollExtent(): Int
Return | |
---|---|
Int |
the vertical extent of the scrollbar's thumb |
computeVerticalScrollOffset
protected open fun computeVerticalScrollOffset(): Int
Return | |
---|---|
Int |
the vertical offset of the scrollbar's thumb |
computeVerticalScrollRange
protected open fun computeVerticalScrollRange(): Int
Return | |
---|---|
Int |
the total vertical range represented by the vertical scrollbar
The default range is the drawing height of this view. |
dispatchDraw
protected open fun dispatchDraw(canvas: Canvas): Unit
Parameters | |
---|---|
canvas |
Canvas: This value cannot be null . |
onConfigurationChanged
protected open fun onConfigurationChanged(newConfig: Configuration!): Unit
Parameters | |
---|---|
newConfig |
Configuration!: The new resource configuration. |
onDraw
protected open fun onDraw(canvas: Canvas): Unit
Parameters | |
---|---|
canvas |
Canvas: the canvas on which the background will be drawn This value cannot be null . |
onFocusChanged
protected open fun onFocusChanged(
focused: Boolean,
direction: Int,
previouslyFocusedRect: Rect?
): Unit
Parameters | |
---|---|
gainFocus |
True if the View has focus; false otherwise. |
direction |
Int: 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. Value is android.view.View#FOCUS_BACKWARD , android.view.View#FOCUS_FORWARD , android.view.View#FOCUS_LEFT , android.view.View#FOCUS_UP , android.view.View#FOCUS_RIGHT , or android.view.View#FOCUS_DOWN |
previouslyFocusedRect |
Rect?: 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. |
onMeasure
protected open fun onMeasure(
widthMeasureSpec: Int,
heightMeasureSpec: Int
): Unit
Parameters | |
---|---|
widthMeasureSpec |
Int: horizontal space requirements as imposed by the parent. The requirements are encoded with android.view.View.MeasureSpec . |
heightMeasureSpec |
Int: vertical space requirements as imposed by the parent. The requirements are encoded with android.view.View.MeasureSpec . |
onOverScrolled
protected open fun onOverScrolled(
scrollX: Int,
scrollY: Int,
clampedX: Boolean,
clampedY: Boolean
): Unit
Parameters | |
---|---|
scrollX |
Int: New X scroll value in pixels |
scrollY |
Int: New Y scroll value in pixels |
clampedX |
Boolean: True if scrollX was clamped to an over-scroll boundary |
clampedY |
Boolean: True if scrollY was clamped to an over-scroll boundary |
onScrollChanged
protected open fun onScrollChanged(
l: Int,
t: Int,
oldl: Int,
oldt: Int
): Unit
Parameters | |
---|---|
l |
Int: Current horizontal scroll origin. |
t |
Int: Current vertical scroll origin. |
oldl |
Int: Previous horizontal scroll origin. |
oldt |
Int: Previous vertical scroll origin. |
onSizeChanged
protected open fun onSizeChanged(
w: Int,
h: Int,
ow: Int,
oh: Int
): Unit
Parameters | |
---|---|
w |
Int: Current width of this view. |
h |
Int: Current height of this view. |
oldw |
Old width of this view. |
oldh |
Old height of this view. |
onVisibilityChanged
protected open fun onVisibilityChanged(
changedView: View,
visibility: Int
): Unit
Parameters | |
---|---|
changedView |
View: The view whose visibility changed. May be this or an ancestor view. This value cannot be null . |
visibility |
Int: The new visibility, one of VISIBLE , INVISIBLE or GONE . Value is android.view.View#VISIBLE , android.view.View#INVISIBLE , or android.view.View#GONE |
onWindowVisibilityChanged
protected open fun onWindowVisibilityChanged(visibility: Int): Unit
Parameters | |
---|---|
visibility |
Int: The new visibility of the window. Value is android.view.View#VISIBLE , android.view.View#INVISIBLE , or android.view.View#GONE |