WebView
public
class
WebView
extends AbsoluteLayout
implements
ViewGroup.OnHierarchyChangeListener,
ViewTreeObserver.OnGlobalFocusChangeListener
| java.lang.Object | ||||
| ↳ | 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 | |
|---|---|
interface |
WebView.FindListener
Interface to listen for find results. |
class |
WebView.HitTestResult
|
interface |
WebView.PictureListener
This interface was deprecated in API level 12. This interface is now obsolete. |
class |
WebView.VisualStateCallback
Callback interface supplied to |
class |
WebView.WebViewTransport
Transportation object for returning WebView across thread boundaries. |
Inherited XML attributes | |
|---|---|
Constants | |
|---|---|
int |
RENDERER_PRIORITY_BOUND
This is the medium binding priority for the WebView renderer process. |
int |
RENDERER_PRIORITY_IMPORTANT
This is the highest binding priority for the WebView renderer process, and the default value WebView uses to bind to the renderer process. |
int |
RENDERER_PRIORITY_WAIVED
This is the lowest binding priority for the WebView renderer process. |
String |
SCHEME_GEO
URI scheme for map address. |
String |
SCHEME_MAILTO
URI scheme for email address. |
String |
SCHEME_TEL
URI scheme for telephone number. |
Inherited constants |
|---|
Inherited fields |
|---|
Public constructors | |
|---|---|
WebView(Context context)
Constructs a new WebView with an Activity Context object. |
|
WebView(Context context, AttributeSet attrs)
Constructs a new WebView with layout parameters. |
|
WebView(Context context, AttributeSet attrs, int defStyleAttr)
Constructs a new WebView with layout parameters and a default style. |
|
WebView(Context context, AttributeSet attrs, int defStyleAttr, boolean privateBrowsing)
This constructor is deprecated.
Private browsing is no longer supported directly via
WebView and will be removed in a future release. Prefer using
|
|
WebView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)
Constructs a new WebView with layout parameters and a default style. |
|
Public methods | |
|---|---|
void
|
addJavascriptInterface(Object object, String name)
Injects the supplied Java object into this WebView. |
void
|
autofill(SparseArray<AutofillValue> values)
Automatically fills the content of the virtual children within this view. |
boolean
|
canGoBack()
Gets whether this WebView has a back history item. |
boolean
|
canGoBackOrForward(int steps)
Gets whether the page can go back or forward the given number of steps. |
boolean
|
canGoForward()
Gets whether this WebView has a forward history item. |
boolean
|
canZoomIn()
This method was deprecated
in API level 17.
This method is prone to inaccuracy due to race conditions
between the web rendering and UI threads; prefer
|
boolean
|
canZoomOut()
This method was deprecated
in API level 17.
This method is prone to inaccuracy due to race conditions
between the web rendering and UI threads; prefer
|
Picture
|
capturePicture()
This method was deprecated
in API level 19.
Use |
void
|
clearCache(boolean includeDiskFiles)
Clears the resource cache. |
static
void
|
clearClientCertPreferences(Runnable onCleared)
Clears the client certificate preferences stored in response to proceeding/cancelling client cert requests. |
void
|
clearFormData()
Removes the autocomplete popup from the currently focused form field, if present. |
void
|
clearHistory()
Tells this WebView to clear its internal back/forward list. |
void
|
clearMatches()
Clears the highlighting surrounding text matches created by
|
void
|
clearSslPreferences()
Clears the SSL preferences table stored in response to proceeding with SSL certificate errors. |
void
|
clearView()
This method was deprecated in API level 18. Use WebView.loadUrl("about:blank") to reliably reset the view state and release page resources (including any running JavaScript). |
void
|
computeScroll()
Called by a parent to request that a child update its values for mScrollX and mScrollY if necessary. |
WebBackForwardList
|
copyBackForwardList()
Gets the WebBackForwardList for this WebView. |
PrintDocumentAdapter
|
createPrintDocumentAdapter(String documentName)
Creates a PrintDocumentAdapter that provides the content of this WebView for printing. |
PrintDocumentAdapter
|
createPrintDocumentAdapter()
This method was deprecated
in API level 21.
Use |
WebMessagePort[]
|
createWebMessageChannel()
Creates a message channel to communicate with JS and returns the message ports that represent the endpoints of this message channel. |
void
|
destroy()
Destroys the internal state of this WebView. |
static
void
|
disableWebView()
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. |
void
|
dispatchCreateViewTranslationRequest(Map<AutofillId, long[]> viewIds, int[] supportedFormats, TranslationCapability capability, List<ViewTranslationRequest> requests)
Dispatch to collect the |
boolean
|
dispatchKeyEvent(KeyEvent event)
Dispatch a key event to the next view on the focus path. |
void
|
documentHasImages(Message response)
Queries the document to see if it contains any image references. |
static
void
|
enableSlowWholeDocumentDraw()
For apps targeting the L release, WebView has a new default behavior that reduces memory footprint and increases performance by intelligently choosing the portion of the HTML document that needs to be drawn. |
void
|
evaluateJavascript(String script, ValueCallback<String> resultCallback)
Asynchronously evaluates JavaScript in the context of the currently displayed page. |
static
String
|
findAddress(String addr)
This method was deprecated
in API level 28.
This method is superseded by |
int
|
findAll(String find)
This method was deprecated
in API level 16.
|
void
|
findAllAsync(String find)
Finds all instances of find on the page and highlights them, asynchronously. |
View
|
findFocus()
Find the view in the hierarchy rooted at this view that currently has focus. |
void
|
findNext(boolean forward)
Highlights and scrolls to the next match found by
|
void
|
flingScroll(int vx, int vy)
|
void
|
freeMemory()
This method was deprecated in API level 19. Memory caches are automatically dropped when no longer needed, and in response to system memory pressure. |
CharSequence
|
getAccessibilityClassName()
Return the class name of this object to be used for accessibility purposes. |
AccessibilityNodeProvider
|
getAccessibilityNodeProvider()
Gets the provider for managing a virtual view hierarchy rooted at this View
and reported to |
SslCertificate
|
getCertificate()
Gets the SSL certificate for the main top-level page or |
int
|
getContentHeight()
Gets the height of the HTML content. |
static
PackageInfo
|
getCurrentWebViewPackage()
If WebView has already been loaded into the current process this method will return the package that was used to load it. |
Bitmap
|
getFavicon()
Gets the favicon for the current page. |
Handler
|
getHandler()
|
WebView.HitTestResult
|
getHitTestResult()
Gets a HitTestResult based on the current cursor node. |
String[]
|
getHttpAuthUsernamePassword(String host, String realm)
This method was deprecated
in API level 26.
Use |
String
|
getOriginalUrl()
Gets the original URL for the current page. |
int
|
getProgress()
Gets the progress for the current page. |
boolean
|
getRendererPriorityWaivedWhenNotVisible()
Return whether this WebView requests a priority of
|
int
|
getRendererRequestedPriority()
Get the requested renderer priority for this WebView. |
static
Uri
|
getSafeBrowsingPrivacyPolicyUrl()
Returns a URL pointing to the privacy policy for Safe Browsing reporting. |
float
|
getScale()
This method was deprecated
in API level 17.
This method is prone to inaccuracy due to race conditions
between the web rendering and UI threads; prefer
|
WebSettings
|
getSettings()
Gets the WebSettings object used to control the settings for this WebView. |
TextClassifier
|
getTextClassifier()
Returns the |
String
|
getTitle()
Gets the title for the current page. |
String
|
getUrl()
Gets the URL for the current page. |
WebChromeClient
|
getWebChromeClient()
Gets the chrome handler. |
static
ClassLoader
|
getWebViewClassLoader()
Returns the |
WebViewClient
|
getWebViewClient()
Gets the WebViewClient. |
Looper
|
getWebViewLooper()
Returns the |
WebViewRenderProcess
|
getWebViewRenderProcess()
Gets a handle to the WebView renderer process associated with this WebView. |
WebViewRenderProcessClient
|
getWebViewRenderProcessClient()
Gets the renderer client object associated with this WebView. |
void
|
goBack()
Goes back in the history of this WebView. |
void
|
goBackOrForward(int steps)
Goes to the history item that is the number of steps away from the current item. |
void
|
goForward()
Goes forward in the history of this WebView. |
void
|
invokeZoomPicker()
Invokes the graphical zoom picker widget for this WebView. |
boolean
|
isPrivateBrowsingEnabled()
Gets whether private browsing is enabled in this WebView. |
boolean
|
isVisibleToUserForAutofill(int virtualId)
Computes whether this virtual autofill view is visible to the user. |
void
|
loadData(String data, String mimeType, String encoding)
Loads the given data into this WebView using a 'data' scheme URL. |
void
|
loadDataWithBaseURL(String baseUrl, String data, String mimeType, String encoding, String historyUrl)
Loads the given data into this WebView, using baseUrl as the base URL for the content. |
void
|
loadUrl(String url)
Loads the given URL. |
void
|
loadUrl(String url, Map<String, String> additionalHttpHeaders)
Loads the given URL with additional HTTP headers, specified as a map from name to value. |
WindowInsets
|
onApplyWindowInsets(WindowInsets insets)
Called when the view should apply |
boolean
|
onCheckIsTextEditor()
Check whether the called view is a text editor, in which case it would make sense to automatically display a soft input window for it. |
void
|
onChildViewAdded(View parent, View child)
This method is deprecated. WebView no longer needs to implement ViewGroup.OnHierarchyChangeListener. This method does nothing now. |
void
|
onChildViewRemoved(View p, View child)
This method is deprecated. WebView no longer needs to implement ViewGroup.OnHierarchyChangeListener. This method does nothing now. |
InputConnection
|
onCreateInputConnection(EditorInfo outAttrs)
Creates a new InputConnection for an InputMethod to interact with the WebView. |
void
|
onCreateVirtualViewTranslationRequests(long[] virtualIds, int[] supportedFormats, Consumer<ViewTranslationRequest> requestsCollector)
Collects |
boolean
|
onDragEvent(DragEvent event)
Handles drag events sent by the system following a call to
|
void
|
onFinishTemporaryDetach()
Called after |
boolean
|
onGenericMotionEvent(MotionEvent event)
Implement this method to handle generic motion events. |
void
|
onGlobalFocusChanged(View oldFocus, View newFocus)
This method is deprecated. WebView should not have implemented ViewTreeObserver.OnGlobalFocusChangeListener. This method does nothing now. |
boolean
|
onHoverEvent(MotionEvent event)
Implement this method to handle hover events. |
boolean
|
onKeyDown(int keyCode, KeyEvent event)
Default implementation of |
boolean
|
onKeyMultiple(int keyCode, int repeatCount, KeyEvent event)
Default implementation of |
boolean
|
onKeyUp(int keyCode, KeyEvent event)
Default implementation of |
void
|
onPause()
Does a best-effort attempt to pause any processing that can be paused safely, such as animations and geolocation. |
void
|
onProvideAutofillVirtualStructure(ViewStructure structure, int flags)
Populates a The |
void
|
onProvideContentCaptureStructure(ViewStructure structure, int flags)
Populates a |
void
|
onProvideVirtualStructure(ViewStructure structure)
Called when assist structure is being retrieved from a view as part of
|
PointerIcon
|
onResolvePointerIcon(MotionEvent event, int pointerIndex)
Resolve the pointer icon that should be used for specified pointer in the motion event. |
void
|
onResume()
Resumes a WebView after a previous call to |
void
|
onStartTemporaryDetach()
This is called when a container is going to temporarily detach a child, with
|
boolean
|
onTouchEvent(MotionEvent event)
Implement this method to handle pointer events. |
boolean
|
onTrackballEvent(MotionEvent event)
Implement this method to handle trackball motion events. |
void
|
onVirtualViewTranslationResponses(LongSparseArray<ViewTranslationResponse> response)
Called when the content from |
void
|
onWindowFocusChanged(boolean hasWindowFocus)
Called when the window containing this view gains or loses focus. |
boolean
|
overlayHorizontalScrollbar()
This method was deprecated in API level 23. This method is now obsolete. |
boolean
|
overlayVerticalScrollbar()
This method was deprecated in API level 23. This method is now obsolete. |
boolean
|
pageDown(boolean bottom)
Scrolls the contents of this WebView down by half the page size. |
boolean
|
pageUp(boolean top)
Scrolls the contents of this WebView up by half the view size. |
void
|
pauseTimers()
Pauses all layout, parsing, and JavaScript timers for all WebViews. |
boolean
|
performLongClick()
Calls this view's OnLongClickListener, if it is defined. |
void
|
postUrl(String url, byte[] postData)
Loads the URL with postData using "POST" method into this WebView. |
void
|
postVisualStateCallback(long requestId, WebView.VisualStateCallback callback)
Posts a |
void
|
postWebMessage(WebMessage message, Uri targetOrigin)
Post a message to main frame. |
void
|
reload()
Reloads the current URL. |
void
|
removeJavascriptInterface(String name)
Removes a previously injected Java object from this WebView. |
boolean
|
requestChildRectangleOnScreen(View child, Rect rect, boolean immediate)
Called when a child of this group wants a particular rectangle to be positioned onto the screen. |
boolean
|
requestFocus(int direction, Rect previouslyFocusedRect)
Call this to try to give focus to a specific view or to one of its descendants
and give it hints about the direction and a specific rectangle that the focus
is coming from.
Looks for a view to give focus to respecting the setting specified by
|
void
|
requestFocusNodeHref(Message hrefMsg)
Requests the anchor or image element URL at the last tapped point. |
void
|
requestImageRef(Message msg)
Requests the URL of the image last touched by the user. |
WebBackForwardList
|
restoreState(Bundle inState)
Restores the state of this WebView from the given Bundle. |
void
|
resumeTimers()
Resumes all layout, parsing, and JavaScript timers for all WebViews. |
void
|
savePassword(String host, String username, String password)
This method was deprecated in API level 18. Saving passwords in WebView will not be supported in future versions. |
WebBackForwardList
|
saveState(Bundle outState)
Saves the state of this WebView used in
|
void
|
saveWebArchive(String filename)
Saves the current view as a web archive. |
void
|
saveWebArchive(String basename, boolean autoname, ValueCallback<String> callback)
Saves the current view as a web archive. |
void
|
setBackgroundColor(int color)
Sets the background color for this view. |
void
|
setCertificate(SslCertificate certificate)
This method was deprecated in API level 17. Calling this function has no useful effect, and will be ignored in future releases. |
static
void
|
setDataDirectorySuffix(String suffix)
Define the directory used to store WebView data for the current process. |
void
|
setDownloadListener(DownloadListener listener)
Registers the interface to be used when content can not be handled by the rendering engine, and should be downloaded instead. |
void
|
setFindListener(WebView.FindListener listener)
Registers the listener to be notified as find-on-page operations progress. |
void
|
setHorizontalScrollbarOverlay(boolean overlay)
This method was deprecated in API level 23. This method has no effect. |
void
|
setHttpAuthUsernamePassword(String host, String realm, String username, String password)
This method was deprecated
in API level 26.
Use |
void
|
setInitialScale(int scaleInPercent)
Sets the initial scale for this WebView. |
void
|
setLayerType(int layerType, Paint paint)
Specifies the type of layer backing this view. |
void
|
setLayoutParams(ViewGroup.LayoutParams params)
Set the layout parameters associated with this view. |
void
|
setMapTrackballToArrowKeys(boolean setMap)
This method was deprecated
in API level 17.
Only the default case, |
void
|
setNetworkAvailable(boolean networkUp)
Informs WebView of the network state. |
void
|
setOverScrollMode(int mode)
Set the over-scroll mode for this view. |
void
|
setPictureListener(WebView.PictureListener listener)
This method was deprecated in API level 15. This method is now obsolete. |
void
|
setRendererPriorityPolicy(int rendererRequestedPriority, boolean waivedWhenNotVisible)
Set the renderer priority policy for this |
static
void
|
setSafeBrowsingWhitelist(List<String> hosts, ValueCallback<Boolean> callback)
Sets the list of hosts (domain names/IP addresses) that are exempt from SafeBrowsing checks. |
void
|
setScrollBarStyle(int style)
Specify the style of the scrollbars. |
void
|
setTextClassifier(TextClassifier textClassifier)
Sets the |
void
|
setVerticalScrollbarOverlay(boolean overlay)
This method was deprecated in API level 23. This method has no effect. |
void
|
setWebChromeClient(WebChromeClient client)
Sets the chrome handler. |
static
void
|
setWebContentsDebuggingEnabled(boolean enabled)
Enables debugging of web contents (HTML / CSS / JavaScript) loaded into any WebViews of this application. |
void
|
setWebViewClient(WebViewClient client)
Sets the WebViewClient that will receive various notifications and requests. |
void
|
setWebViewRenderProcessClient(Executor executor, WebViewRenderProcessClient webViewRenderProcessClient)
Sets the renderer client object associated with this WebView. |
void
|
setWebViewRenderProcessClient(WebViewRenderProcessClient webViewRenderProcessClient)
Sets the renderer client object associated with this WebView. |
boolean
|
shouldDelayChildPressedState()
Return true if the pressed state should be delayed for children or descendants of this ViewGroup. |
boolean
|
showFindDialog(String text, boolean showIme)
This method was deprecated in API level 18. This method does not work reliably on all Android versions; implementing a custom find dialog using WebView.findAllAsync() provides a more robust solution. |
static
void
|
startSafeBrowsing(Context context, ValueCallback<Boolean> callback)
Starts Safe Browsing initialization. |
void
|
stopLoading()
Stops the current load. |
void
|
zoomBy(float zoomFactor)
Performs a zoom operation in this WebView. |
boolean
|
zoomIn()
Performs zoom in in this WebView. |
boolean
|
zoomOut()
Performs zoom out in this WebView. |
Protected methods | |
|---|---|
int
|
computeHorizontalScrollOffset()
Compute the horizontal offset of the horizontal scrollbar's thumb within the horizontal range. |
int
|
computeHorizontalScrollRange()
Compute the horizontal range that the horizontal scrollbar represents. |
int
|
computeVerticalScrollExtent()
Compute the vertical extent of the vertical scrollbar's thumb within the vertical range. |
int
|
computeVerticalScrollOffset()
Compute the vertical offset of the vertical scrollbar's thumb within the horizontal range. |
int
|
computeVerticalScrollRange()
Compute the vertical range that the vertical scrollbar represents. |
void
|
dispatchDraw(Canvas canvas)
Called by draw to draw the child views. |
void
|
onAttachedToWindow()
This is called when the view is attached to a window. |
void
|
onConfigurationChanged(Configuration newConfig)
Called when the current configuration of the resources being used by the application have changed. |
void
|
onDraw(Canvas canvas)
Implement this to do your drawing. |
void
|
onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect)
Called by the view system when the focus state of this view changes. |
void
|
onMeasure(int widthMeasureSpec, int heightMeasureSpec)
Measure the view and its content to determine the measured width and the measured height. |
void
|
onOverScrolled(int scrollX, int scrollY, boolean clampedX, boolean clampedY)
Called by |
void
|
onScrollChanged(int l, int t, int oldl, int oldt)
This is called in response to an internal scroll in this view (i.e., the view scrolled its own contents). |
void
|
onSizeChanged(int w, int h, int ow, int oh)
This is called during layout when the size of this view has changed. |
void
|
onVisibilityChanged(View changedView, int visibility)
Called when the visibility of the view or an ancestor of the view has changed. |
void
|
onWindowVisibilityChanged(int visibility)
Called when the window containing has change its visibility
(between |
Inherited methods | |
|---|---|
Constants
RENDERER_PRIORITY_BOUND
public static final int RENDERER_PRIORITY_BOUND
This is the medium binding priority for the WebView renderer process. This is equivalent to
the standard priority used by the system for calls to Context.bindService(android.content.Intent, android.content.ServiceConnection, int) when no flags are
provided. At this priority level WebView renderers will be slightly more likely
targets for being killed when the system is running low on memory.
If using this priority, we recommend handling the WebViewClient.onRenderProcessGone(WebView, RenderProcessGoneDetail) callback to recover from low memory kills as well as other
types of renderer crashes.
See also:
Constant Value: 1 (0x00000001)
RENDERER_PRIORITY_IMPORTANT
public static final int RENDERER_PRIORITY_IMPORTANT
This is the highest binding priority for the WebView renderer process, and the default value
WebView uses to bind to the renderer process. This is equivalent to Context.BIND_IMPORTANT. At this priority level WebView renderers are less likely to
be killed when the system is running low on memory and will have the same priority as your
app's main process.
It's still possible for the renderer process to be killed when the system is running low
on memory, however specifying this priority makes this situation less likely. It's also still
possible for the renderer process to crash for other reasons. You may optionally still choose
to handle WebViewClient.onRenderProcessGone in order to recover from a killed or
crashed renderer process.
See also:
Constant Value: 2 (0x00000002)
RENDERER_PRIORITY_WAIVED
public static final int RENDERER_PRIORITY_WAIVED
This is the lowest binding priority for the WebView renderer process. This is equivalent to
Context.BIND_WAIVE_PRIORITY. At this priority level WebView renderers will be
frequent targets for being killed when the system is running low on memory.
If using this priority, we recommend handling the WebViewClient.onRenderProcessGone(WebView, RenderProcessGoneDetail) callback to recover from low memory kills as well as other
types of renderer crashes.
See also:
Constant Value: 0 (0x00000000)
SCHEME_GEO
public static final String SCHEME_GEO
URI scheme for map address.
Constant Value: "geo:0,0?q="
SCHEME_MAILTO
public static final String SCHEME_MAILTO
URI scheme for email address.
Constant Value: "mailto:"
SCHEME_TEL
public static final String SCHEME_TEL
URI scheme for telephone number.
Constant Value: "tel:"
Public constructors
WebView
public 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
public WebView (Context context, AttributeSet attrs)
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
public WebView (Context context, AttributeSet attrs, int defStyleAttr)
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
public WebView (Context context, AttributeSet attrs, int defStyleAttr, boolean privateBrowsing)
This constructor is 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 |
WebView
public WebView (Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)
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. |
Public methods
addJavascriptInterface
public void addJavascriptInterface (Object object, String name)
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 Build.VERSION_CODES.JELLY_BEAN_MR1
and above, only public methods that are annotated with
JavascriptInterface can be accessed from JavaScript.
For applications targeted to API level 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("html", "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
Build.VERSION_CODES.JELLY_BEANor earlier. Apps that target a version later thanBuild.VERSION_CODES.JELLY_BEANare 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 targetBuild.VERSION_CODES.JELLY_BEAN_MR1and 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
Build.VERSION_CODES.LOLLIPOPand above, methods of injected Java objects are enumerable from JavaScript.
| Parameters | |
|---|---|
object |
Object: 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
public void autofill (SparseArray<AutofillValue> values)
Automatically fills the content of the virtual children within this view.
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.
onProvideAutofillVirtualStructure(android.view.ViewStructure, int) is responsible for the
former, this method is responsible for the latter - see autofill(android.view.autofill.AutofillValue) and
onProvideAutofillVirtualStructure(android.view.ViewStructure, int) for more info about autofill.
If a child value is updated asynchronously, the next call to
AutofillManager.notifyValueChanged(View, int, AutofillValue) must happen
after the value was changed to the autofilled value. If not, the child will not be
considered autofilled.
Note: To indicate that a virtual view was autofilled,
?android:attr/autofilledHighlight should be drawn over it until the data
changes.
| Parameters | |
|---|---|
values |
SparseArray: map of values to be autofilled, keyed by virtual child id.
This value cannot be null. |
canGoBack
public boolean canGoBack ()
Gets whether this WebView has a back history item.
| Returns | |
|---|---|
boolean |
true if this WebView has a back history item |
canGoBackOrForward
public boolean canGoBackOrForward (int steps)
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 |
| Returns | |
|---|---|
boolean |
|
canGoForward
public boolean canGoForward ()
Gets whether this WebView has a forward history item.
| Returns | |
|---|---|
boolean |
true if this WebView has a forward history item |
canZoomIn
public boolean canZoomIn ()
This method was deprecated
in API level 17.
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.
| Returns | |
|---|---|
boolean |
true if this WebView can be zoomed in |
canZoomOut
public boolean canZoomOut ()
This method was deprecated
in API level 17.
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.
| Returns | |
|---|---|
boolean |
true if this WebView can be zoomed out |
capturePicture
public Picture capturePicture ()
This method was deprecated
in API level 19.
Use onDraw(Canvas) to obtain a bitmap snapshot of the WebView, or
saveWebArchive(String) 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
Build.VERSION_CODES.HONEYCOMB and
Build.VERSION_CODES.ICE_CREAM_SANDWICH inclusive, the
picture does not include fixed position elements or scrollable divs.
Note that from 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.
| Returns | |
|---|---|
Picture |
a picture that captures the current contents of this WebView |
clearCache
public void clearCache (boolean includeDiskFiles)
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
public static void clearClientCertPreferences (Runnable onCleared)
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
public void clearFormData ()
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
public void clearHistory ()
Tells this WebView to clear its internal back/forward list.
clearMatches
public void clearMatches ()
Clears the highlighting surrounding text matches created by
findAllAsync(String).
clearSslPreferences
public void clearSslPreferences ()
Clears the SSL preferences table stored in response to proceeding with SSL certificate errors.
clearView
public void clearView ()
This method was deprecated
in API level 18.
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.
computeScroll
public void computeScroll ()
Called by a parent to request that a child update its values for mScrollX
and mScrollY if necessary. This will typically be done if the child is
animating a scroll using a Scroller
object.
copyBackForwardList
public WebBackForwardList copyBackForwardList ()
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.
| Returns | |
|---|---|
WebBackForwardList |
This value cannot be null. |
createPrintDocumentAdapter
public PrintDocumentAdapter createPrintDocumentAdapter (String documentName)
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
PrintDocumentAdapter for more information.
| Parameters | |
|---|---|
documentName |
String: The user-facing name of the printed document. See
PrintDocumentInfo
This value cannot be null. |
| Returns | |
|---|---|
PrintDocumentAdapter |
This value cannot be null. |
createPrintDocumentAdapter
public PrintDocumentAdapter createPrintDocumentAdapter ()
This method was deprecated
in API level 21.
Use createPrintDocumentAdapter(java.lang.String) which requires user
to provide a print document name.
| Returns | |
|---|---|
PrintDocumentAdapter |
|
createWebMessageChannel
public WebMessagePort[] createWebMessageChannel ()
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.
| Returns | |
|---|---|
WebMessagePort[] |
the two message ports that form the message channel.
This value cannot be null. |
destroy
public void destroy ()
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
public static void disableWebView ()
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(String)).
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 Service.onCreate().
| Throws | |
|---|---|
IllegalStateException |
if WebView has already been initialized in the current process. |
dispatchCreateViewTranslationRequest
public void dispatchCreateViewTranslationRequest (Map<AutofillId, long[]> viewIds, int[] supportedFormats, TranslationCapability capability, List<ViewTranslationRequest> requests)
Dispatch to collect the ViewTranslationRequests 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 ViewTranslationRequests and create a
Translator to translate the requests. All the
ViewTranslationRequests 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(Map, int, TranslationCapability, List) for all the child
views.
| Parameters | |
|---|---|
viewIds |
Map: This value cannot be null. |
supportedFormats |
int: This value cannot be null.
Value is TranslationSpec.DATA_FORMAT_TEXT |
capability |
TranslationCapability: This value may be null. |
requests |
List: This value cannot be null. |
dispatchKeyEvent
public boolean dispatchKeyEvent (KeyEvent event)
Dispatch a key event to the next view on the focus path. This path runs from the top of the view tree down to the currently focused view. If this view has focus, it will dispatch to itself. Otherwise it will dispatch the next node down the focus path. This method also fires any key listeners.
| Parameters | |
|---|---|
event |
KeyEvent: The key event to be dispatched. |
| Returns | |
|---|---|
boolean |
True if the event was handled, false otherwise. |
documentHasImages
public void documentHasImages (Message response)
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
public static void enableSlowWholeDocumentDraw ()
For apps targeting the L release, WebView has a new default behavior that reduces memory footprint and increases performance by intelligently choosing the portion of the HTML document that needs to be drawn. These optimizations are transparent to the developers. However, under certain circumstances, an App developer may want to disable them:
- When an app uses
onDraw(Canvas)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
public void evaluateJavascript (String script, ValueCallback<String> resultCallback)
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 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(Object, String) instead to persist JavaScript objects across navigations.
| Parameters | |
|---|---|
script |
String: the JavaScript to execute.
This value cannot be null. |
resultCallback |
ValueCallback: 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
public static String findAddress (String addr)
This method was deprecated
in API level 28.
This method is superseded by TextClassifier.generateLinks(
android.view.textclassifier.TextLinks.Request). 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
Build.VERSION_CODES.O_MR1 and earlier, it also causes
the entire WebView implementation to be loaded and initialized, which
can throw AndroidRuntimeException or other exceptions
if the WebView implementation is currently being updated.
| Parameters | |
|---|---|
addr |
String: the string to search for addresses |
| Returns | |
|---|---|
String |
the address, or if no address is found, null |
findAll
public int findAll (String find)
This method was deprecated
in API level 16.
findAllAsync(String) is preferred.
Finds all instances of find on the page and highlights them.
Notifies any registered FindListener.
| Parameters | |
|---|---|
find |
String: the string to find |
| Returns | |
|---|---|
int |
the number of occurrences of the String "find" that were found |
See also:
findAllAsync
public void findAllAsync (String find)
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
public View findFocus ()
Find the view in the hierarchy rooted at this view that currently has focus.
| Returns | |
|---|---|
View |
The view that currently has focus, or null if no focused view can be found. |
findNext
public void findNext (boolean forward)
Highlights and scrolls to the next match found by
findAllAsync(String), 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
public void freeMemory ()
This method was deprecated
in API level 19.
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.
getAccessibilityClassName
public CharSequence getAccessibilityClassName ()
Return the class name of this object to be used for accessibility purposes.
Subclasses should only override this if they are implementing something that
should be seen as a completely new class of view when used by accessibility,
unrelated to the class it is deriving from. This is used to fill in
AccessibilityNodeInfo.setClassName.
| Returns | |
|---|---|
CharSequence |
|
getAccessibilityNodeProvider
public AccessibilityNodeProvider getAccessibilityNodeProvider ()
Gets the provider for managing a virtual view hierarchy rooted at this View
and reported to AccessibilityServices
that explore the window content.
If this method returns an instance, this instance is responsible for managing
AccessibilityNodeInfos describing the virtual sub-tree rooted at this
View including the one representing the View itself. Similarly the returned
instance is responsible for performing accessibility actions on any virtual
view or the root view itself.
If an AccessibilityDelegate has been specified via calling
setAccessibilityDelegate(android.view.View.AccessibilityDelegate) its
AccessibilityDelegate.getAccessibilityNodeProvider(View)
is responsible for handling this call.
| Returns | |
|---|---|
AccessibilityNodeProvider |
The provider. |
getCertificate
public SslCertificate getCertificate ()
Gets the SSL certificate for the main top-level page or null if there is
no certificate (the site is not secure).
| Returns | |
|---|---|
SslCertificate |
the SSL certificate for the main top-level page |
getContentHeight
public int getContentHeight ()
Gets the height of the HTML content.
| Returns | |
|---|---|
int |
the height of the HTML content |
getCurrentWebViewPackage
public static PackageInfo getCurrentWebViewPackage ()
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.
| Returns | |
|---|---|
PackageInfo |
the current WebView package, or null if there is none. |
getFavicon
public Bitmap getFavicon ()
Gets the favicon for the current page. This is the favicon of the current page until WebViewClient.onReceivedIcon is called.
| Returns | |
|---|---|
Bitmap |
the favicon for the current page or null if the page doesn't
have one or if no page has been loaded |
getHandler
public Handler getHandler ()
| Returns | |
|---|---|
Handler |
A handler associated with the thread running the View. This handler can be used to pump events in the UI events queue. |
getHitTestResult
public WebView.HitTestResult getHitTestResult ()
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(Message) asynchronously. If a HTML::img tag is
found, the HitTestResult type is set to IMAGE_TYPE and the URL is set in
the "extra" field. A type of
SRC_IMAGE_ANCHOR_TYPE indicates an anchor with a URL that has an image as
a child node. If a phone number is found, the HitTestResult type is set
to PHONE_TYPE and the phone number is set in the "extra" field of
HitTestResult. If a map address is found, the HitTestResult type is set
to GEO_TYPE and the address is set in the "extra" field of HitTestResult.
If an email address is found, the HitTestResult type is set to EMAIL_TYPE
and the email is set in the "extra" field of HitTestResult. Otherwise,
HitTestResult type is set to UNKNOWN_TYPE.
| Returns | |
|---|---|
WebView.HitTestResult |
This value cannot be null. |
getHttpAuthUsernamePassword
public String[] getHttpAuthUsernamePassword (String host, String realm)
This method was deprecated
in API level 26.
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 |
| Returns | |
|---|---|
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
public String getOriginalUrl ()
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.
| Returns | |
|---|---|
String |
the URL that was originally requested for the current page or
null if no page has been loaded |
getProgress
public int getProgress ()
Gets the progress for the current page.
| Returns | |
|---|---|
int |
the progress for the current page between 0 and 100 |
getRendererPriorityWaivedWhenNotVisible
public boolean getRendererPriorityWaivedWhenNotVisible ()
Return whether this WebView requests a priority of
RENDERER_PRIORITY_WAIVED when not visible.
| Returns | |
|---|---|
boolean |
whether this WebView requests a priority of
RENDERER_PRIORITY_WAIVED when not visible. |
getRendererRequestedPriority
public int getRendererRequestedPriority ()
Get the requested renderer priority for this WebView.
| Returns | |
|---|---|
int |
the requested renderer priority policy.
Value is RENDERER_PRIORITY_WAIVED, RENDERER_PRIORITY_BOUND, or RENDERER_PRIORITY_IMPORTANT |
getSafeBrowsingPrivacyPolicyUrl
public static Uri getSafeBrowsingPrivacyPolicyUrl ()
Returns a URL pointing to the privacy policy for Safe Browsing reporting.
| Returns | |
|---|---|
Uri |
the url pointing to a privacy policy document which can be displayed to users.
This value cannot be null. |
getScale
public float getScale ()
This method was deprecated
in API level 17.
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.
| Returns | |
|---|---|
float |
the current scale |
getSettings
public WebSettings getSettings ()
Gets the WebSettings object used to control the settings for this WebView.
| Returns | |
|---|---|
WebSettings |
a WebSettings object that can be used to control this WebView's
settings
This value cannot be null. |
getTextClassifier
public TextClassifier getTextClassifier ()
Returns the TextClassifier used by this WebView.
If no TextClassifier has been set, this WebView uses the default set by the system.
| Returns | |
|---|---|
TextClassifier |
This value cannot be null. |
getTitle
public String getTitle ()
Gets the title for the current page. This is the title of the current page until WebViewClient.onReceivedTitle is called.
| Returns | |
|---|---|
String |
the title for the current page or null if no page has been loaded |
getUrl
public String getUrl ()
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.
| Returns | |
|---|---|
String |
the URL for the current page or null if no page has been loaded |
getWebChromeClient
public WebChromeClient getWebChromeClient ()
Gets the chrome handler.
| Returns | |
|---|---|
WebChromeClient |
the WebChromeClient, or null if not yet set |
See also:
getWebViewClassLoader
public static ClassLoader getWebViewClassLoader ()
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.
| Returns | |
|---|---|
ClassLoader |
This value cannot be null. |
getWebViewClient
public WebViewClient getWebViewClient ()
Gets the WebViewClient.
| Returns | |
|---|---|
WebViewClient |
the WebViewClient, or a default client if not yet set
This value cannot be null. |
See also:
getWebViewLooper
public Looper getWebViewLooper ()
Returns the Looper corresponding to the thread on which WebView calls must be made.
| Returns | |
|---|---|
Looper |
This value cannot be null. |
getWebViewRenderProcess
public WebViewRenderProcess getWebViewRenderProcess ()
Gets a handle to the WebView renderer process associated with this WebView.
In 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.
| Returns | |
|---|---|
WebViewRenderProcess |
the WebViewRenderProcess renderer handle associated
with this WebView, or null if
WebView is not runing in multiprocess mode. |
getWebViewRenderProcessClient
public WebViewRenderProcessClient getWebViewRenderProcessClient ()
Gets the renderer client object associated with this WebView.
| Returns | |
|---|---|
WebViewRenderProcessClient |
the WebViewRenderProcessClient object associated with this WebView, if one
has been set via setWebViewRenderProcessClient(android.webkit.WebViewRenderProcessClient)
or null otherwise. |
goBackOrForward
public void goBackOrForward (int steps)
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
public void goForward ()
Goes forward in the history of this WebView.
invokeZoomPicker
public void invokeZoomPicker ()
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
public boolean isPrivateBrowsingEnabled ()
Gets whether private browsing is enabled in this WebView.
| Returns | |
|---|---|
boolean |
|
isVisibleToUserForAutofill
public boolean isVisibleToUserForAutofill (int virtualId)
Computes whether this virtual autofill view is visible to the user.
Note: By default it returns true, but views providing a virtual hierarchy
view must override it.
| Parameters | |
|---|---|
virtualId |
int |
| Returns | |
|---|---|
boolean |
Whether the view is visible on the screen. |
loadData
public void loadData (String data, String mimeType, String encoding)
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 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 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
public void loadDataWithBaseURL (String baseUrl, String data, String mimeType, String encoding, String historyUrl)
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
public void loadUrl (String url)
Loads the given URL.
Also see compatibility note on evaluateJavascript(String, ValueCallback).
| Parameters | |
|---|---|
url |
String: the URL of the resource to load
This value cannot be null. |
loadUrl
public void loadUrl (String url, Map<String, String> additionalHttpHeaders)
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(String, ValueCallback).
| Parameters | |
|---|---|
url |
String: the URL of the resource to load
This value cannot be null. |
additionalHttpHeaders |
Map: map with additional headers
This value cannot be null. |
onApplyWindowInsets
public WindowInsets onApplyWindowInsets (WindowInsets insets)
Called when the view should apply WindowInsets according to its internal policy.
This method should be overridden by views that wish to apply a policy different from or
in addition to the default behavior. Clients that wish to force a view subtree
to apply insets should call dispatchApplyWindowInsets(android.view.WindowInsets).
Clients may supply an OnApplyWindowInsetsListener to a view. If one is set
it will be called during dispatch instead of this method. The listener may optionally
call this method from its own implementation if it wishes to apply the view's default
insets policy in addition to its own.
Implementations of this method should either return the insets parameter unchanged
or a new WindowInsets cloned from the supplied insets with any insets consumed
that this view applied itself. This allows new inset types added in future platform
versions to pass through existing implementations unchanged without being erroneously
consumed.
By default if a view's fitsSystemWindows
property is set then the view will consume the system window insets and apply them
as padding for the view.
| Parameters | |
|---|---|
insets |
WindowInsets: Insets to apply |
| Returns | |
|---|---|
WindowInsets |
The supplied insets with any applied insets consumed |
onCheckIsTextEditor
public boolean onCheckIsTextEditor ()
Check whether the called view is a text editor, in which case it
would make sense to automatically display a soft input window for
it. Subclasses should override this if they implement
onCreateInputConnection(android.view.inputmethod.EditorInfo) to return true if
a call on that method would return a non-null InputConnection, and
they are really a first-class editor that the user would normally
start typing on when the go into a window containing your view.
The default implementation always returns false. This does
not mean that its onCreateInputConnection(android.view.inputmethod.EditorInfo)
will not be called or the user can not otherwise perform edits on your
view; it is just a hint to the system that this is not the primary
purpose of this view.
| Returns | |
|---|---|
boolean |
Returns true if this view is a text editor, else false. |
onChildViewAdded
public void onChildViewAdded (View parent, View child)
This method is deprecated.
WebView no longer needs to implement
ViewGroup.OnHierarchyChangeListener. This method does nothing now.
Called when a new child is added to a parent view.
| Parameters | |
|---|---|
parent |
View: the view in which a child was added |
child |
View: the new child view added in the hierarchy |
onChildViewRemoved
public void onChildViewRemoved (View p, View child)
This method is deprecated.
WebView no longer needs to implement
ViewGroup.OnHierarchyChangeListener. This method does nothing now.
Called when a child is removed from a parent view.
| Parameters | |
|---|---|
p |
View: the view from which the child was removed |
child |
View: the child removed from the hierarchy |
onCreateInputConnection
public InputConnection onCreateInputConnection (EditorInfo outAttrs)
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. |
| Returns | |
|---|---|
InputConnection |
|
onCreateVirtualViewTranslationRequests
public void onCreateVirtualViewTranslationRequests (long[] virtualIds,
int[] supportedFormats,
Consumer<ViewTranslationRequest> requestsCollector)Collects ViewTranslationRequests 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(ViewStructure, int) and the system determined that
those virtual views were relevant for translation.
The default implementation does nothing.
| Parameters | |
|---|---|
virtualIds |
long: This value cannot be null. |
supportedFormats |
int: This value cannot be null.
Value is TranslationSpec.DATA_FORMAT_TEXT |
requestsCollector |
Consumer: This value cannot be null. |
| Returns | |
|---|---|
void |
This value may be null. |
onDragEvent
public boolean onDragEvent (DragEvent event)
Handles drag events sent by the system following a call to
startDragAndDrop().
The system calls this method and passes a DragEvent object in response to drag and
drop events. This method can then call DragEvent.getAction() to determine the state
of the drag and drop operation.
The default implementation returns false unless an OnReceiveContentListener
has been set for this view (see setOnReceiveContentListener(String, OnReceiveContentListener)), in which case
the default implementation does the following:
- Returns
truefor anACTION_DRAG_STARTEDevent - Calls
performReceiveContent(ContentInfo)for anACTION_DROPevent - Returns
truefor anACTION_DROPevent if theOnReceiveContentListenerconsumed some or all of the content
| 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. |
| Returns | |
|---|---|
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 |
onFinishTemporaryDetach
public void onFinishTemporaryDetach ()
Called after onStartTemporaryDetach() when the container is done
changing the view.
onGenericMotionEvent
public boolean onGenericMotionEvent (MotionEvent event)
Implement this method to handle generic motion events.
Generic motion events describe joystick movements, hover events from mouse or stylus
devices, trackpad touches, scroll wheel movements and other motion events not handled
by onTouchEvent(android.view.MotionEvent) or onTrackballEvent(android.view.MotionEvent).
The source of the motion event specifies
the class of input that was received. Implementations of this method
must examine the bits in the source before processing the event.
The following code example shows how this is done.
Generic motion events with source class InputDevice.SOURCE_CLASS_POINTER
are delivered to the view under the pointer. All other generic motion events are
delivered to the focused view.
public boolean onGenericMotionEvent(MotionEvent event) {
if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
if (event.getAction() == MotionEvent.ACTION_MOVE) {
// process the joystick movement...
return true;
}
}
if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
switch (event.getAction()) {
case MotionEvent.ACTION_HOVER_MOVE:
// process the hover movement...
return true;
case MotionEvent.ACTION_SCROLL:
// process the scroll wheel movement...
return true;
}
}
return super.onGenericMotionEvent(event);
}| Parameters | |
|---|---|
event |
MotionEvent: The generic motion event being processed. |
| Returns | |
|---|---|
boolean |
True if the event was handled, false otherwise. |
onGlobalFocusChanged
public void onGlobalFocusChanged (View oldFocus, View newFocus)
This method is deprecated.
WebView should not have implemented
ViewTreeObserver.OnGlobalFocusChangeListener. This method does nothing now.
Callback method to be invoked when the focus changes in the view tree. When the view tree transitions from touch mode to non-touch mode, oldFocus is null. When the view tree transitions from non-touch mode to touch mode, newFocus is null. When focus changes in non-touch mode (without transition from or to touch mode) either oldFocus or newFocus can be null.
| Parameters | |
|---|---|
oldFocus |
View: The previously focused view, if any. |
newFocus |
View: The newly focused View, if any. |