5 years ago (2016-01-15)  Algorithm language |   First to comment  94 
post score 1 times, average 4.0

WebView is a control for displaying web pages under Android. Using it can implement a simple browser to access web pages on the Internet.It can also be used as a local text display control, similar to textView.WebView or TextView is used to display HTML content. There are big differences in the way they interact. Take the image click event in HTML content as an example. In WebView mode, developers need to respond to a click event by injecting JavaScript code. The Android system provides a mechanism for a JavaScript web page script in a WebView to call a Java class method; in the TextView, the image is parsed as an ImageSpan and responds by registering a click event on ImageSpan. webview display rich text  

One, webview shows rich text

For example iniHtml is a string of HTML code, use

This html can be displayed on the webview.  

Second, webview display project resources in the web page file

We can put an html file index.html under the project assets file, use WebView.loadUrl ("file:///android_asset/index.html") to display the html file, in this html file if you want to reference the asserts file The folder css and js files are also accessed using file:///android_asset/ ;.

Third, java call javascript function

Call java code using loadurl

Fourth, javascript how to call java function

Calling external java functions in webview using javascript allows the android webview to display rich text with a more native experience, without the user feeling that he is using a browser to view your display text.In order to allow javascript to call java code, Android takes a window object M in javascript and object N in java as a binding or mapping, so that the operation of M in javascript is equivalent to that in java. The operation.

Implementation method: webview enabled javascript, binding js object

addJavascriptInterface(Object object, String name) The first parameter in the function object is the object under java, and name is the object name mapped under javascript.You can declare a click() function for an object under java, such as the current activity, and use window.name.click() in javascript to start the java click function. It should be noted that the click function in java needs to add a declaration @JavascriptInterface


This article has been printed on copyright and is protected by copyright laws. It must not be reproduced without permission.If you need to reprint, please contact the author or visit the copyright to obtain the authorization. If you feel that this article is useful to you, you can click the "Sponsoring Author" below to call the author!

Reprinted Note Source: Baiyuan's Blog>>https://wangbaiyuan.cn/en/webview-shows-rich-text-interact-with-js-java-2.html

Post comment


No Comment


Forget password?