Explain in detail the problem of interactive value transfer between WebView and JS

With the popularity of mixed development mode, we need to use WebView to load web pages on the basis of native, which is more convenient to control. Today, let's take a look at how to pass the values of Java objects and list collections to JS calls.

How to pass values of Java object instances to JS

In fact, it is very simple for us to pass the value of Java object instances to JS recognized and usable objects in Android native. Let's take an example.

HTML file

We wrote an HTML file locally and put it in the assets directory.

See the person in the calljs () function? It is the Java object instance we pass values to. You can use it directly to get the age, name, and gender attributes. How can we declare this object before it is recognized by JS?

Java object

Let's see how we created the entity class person. The code is as follows:

See the @ javascriptinterface annotation on each get method in our entity class person? It means to tell JS that this can be used, so we can use the corresponding method of person. Get () in the HTML file to get the content.

The value is passed on WebView as follows:

wv.addJavascriptInterface(p,“person”); This means that the Java object P is injected into WebView as person. When JS is called, the corresponding person is person.

wv.loadUrl(“JavaScript:callJS()”); The meaning of this sentence is to call the calljs () function method in JS.

How to pass Java list to JS?

In fact, according to the truth, you can't directly pass the list set to JS for use. However, since objects can pass values, JS can call Java objects or methods in Android, we'll pass it in the form of splitting.

HTML file

Split value transfer

How to split it? It is called the method in Android in JS, which can return the object in the collection according to index, and then get the attribute in the object. The code is as follows:

All codes in the whole acitvity

design sketch

Thank you for reading, hope to help you, thank you for your support to this site!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>