Android WebView Application Interface Development Tutorial _android

Source: Internet
Author: User
Tags object object

The WebView component itself is a browser implementation, Android5.0 enhanced WebView is based on chromium M37, which directly supports WEBRTC, Webaudio, and WebGL. Developers can use aggregation (polymer) and material design directly in WebView.

I. WebView browsing Web page (load line URL)

WebView provides a number of ways to perform browser operations, the usual methods are as follows:

void GoBack (): Back
void GoForward (): Forward.
void Gobackorforward (int step): The step is a positive forward, and step is a negative indication of backward.
void Loadurl (String URL): Loads the Web page that corresponds to the specified URL.
Boolean zoomin (): Enlarges the Web page.
Boolean zoomout (): Shrinking Web pages.

Example: Mini Browser

The example contains two interfaces, the first interface includes an input URL and an open URL, and the second interface contains a webview that displays the interface for the URL entered by the first interface. The program code is as follows:

First interface

public class Mainactivity extends Appcompatactivity {
private edittext mediturl;
Private Button Mbtnopen;
@Override
protected void onCreate (Bundle savedinstancestate) {
super.oncreate (savedinstancestate);
Setcontentview (r.layout.activity_main);
Mediturl = (edittext) Findviewbyid (r.id.edit_url);
Mbtnopen = (Button) Findviewbyid (r.id.btn_open);
Mbtnopen.setonclicklistener (New View.onclicklistener () {
@Override public
void OnClick (View v) {
Intent Intent = new Intent (mainactivity.this, webviewactivity.class);
String URL = mediturl.gettext (). toString ();
Intent.putextra ("url", url);
StartActivity (intent);}}
);
}

This interface is very simple, an input box, a button, respectively for the input URL and open WebView.

A second interface

public class Webviewactivity extends Appcompatactivity {
private webview Mwebview;
@Override
protected void onCreate (Bundle savedinstancestate) {
super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_web_view);
Mwebview = (webview) Findviewbyid (R.id.web_view);
Intent Intent = Getintent ();
String url = intent.getstringextra ("url");
Mwebview.loadurl (URL);
Mwebview.getsettings (). Setjavascriptenabled (true);
Mwebview.setwebviewclient (New Webviewclient () {
});
}
@Override public
void onbackpressed () {
if (Mwebview!= null && mwebview.cangoback ()) {
Mwebview.goback ();
} else {
super.onbackpressed ();}}}

This code calls the WebView loadurl (String url) method to load, display the page corresponding to the URL, and set it to support JavaScript. If you jump to the browser during WebView, the webviewclient is displayed in WebView by setting the.

The onbackpressed () method is also written, and when the webview is not empty and webview can be rolled back, the previous WebView interface is returned instead of going back to the previous activity directly.

Because the application requires access to the Internet, it needs to be configured in Androidmanifest.xml:

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

The effect of the instance is shown below:

Two. WebView Load HTML code

WebView provides a loaddata (string data, String mimetype, String encoding) method that can be used to load and display HTML code, but this method can occur garbled.

WebView also provides a loaddatawithbaseurl (string baseurl, String data, String mimetype, String encoding, String Historyurl) method, The method is an enhanced version of the LoadData (string data, String mimetype, String encoding) method and does not produce garbled characters. Several parameters of the method are described:

Data: Specifies the HTML code to load.

MimeType: Specifies the MIME type of HTML, which can be specified as text/html for HTML.

Encoding: Specifies the character set used for HTML code encoding, such as GBK.

WebView Load HTML code:

public class Mainactivity extends Appcompatactivity {
private webview Mshowwebview;
@Override
protected void onCreate (Bundle savedinstancestate) {
super.oncreate (savedinstancestate);
Setcontentview (r.layout.activity_main);
Mshowwebview = (webview) Findviewbyid (R.id.show_web_view);
StringBuilder sb = new StringBuilder ();
Stitching a section of HTML code
sb.append (" 
 

The instance works as follows:

Three. JavaScript in WebView calls the Android method

It takes three steps to invoke the Android method in WebView:

The setjavascriptenabled (true) of the websettings associated with WebView is invoked to enable the JavaScript invocation feature.

Invokes the WebView Addjavascriptinterface (object, String name) method to expose an object object to a JavaScript object.

Invoke the Android method with the name object you just exposed in the JavaScript script.

Write an instance of calling the Android method in JavaScript, which contains a WebView component for displaying HTML pages. The activity code is as follows:

public class Mainactivity extends Appcompatactivity {
private webview Mwebview;
@Override
protected void onCreate (Bundle savedinstancestate) {
super.oncreate (savedinstancestate);
Setcontentview (r.layout.activity_main);
Mwebview = (webview) Findviewbyid (R.id.web_view);
Loads the HTML page
mwebview.loadurl ("file:///android_asset/test.html") under the local assets directory using the file protocol;
Gets the set object of the WebView
websettings websettings = mwebview.getsettings ();
Open JavaScript call
websettings.setjavascriptenabled (true);
Exposes the MyObject object to the JavaScript object
Mwebview.addjavascriptinterface (this), myobj);

In the code above, the function of JavaScript to invoke the Android method is opened, and the MyObject object in the Android application is exposed to the JavaScript script, exposing the object named MyObj in the JavaScript script.

The MyObject code is as follows:

public class MyObject {
private context context;
Public MyObject {
This.context = context;
}
This method will be exposed to JavaScript script calls
@JavascriptInterface public
void Showtoast (String name) {
Toast.maketext ( Context, name + ", Hello!" ", Toast.length_short). Show ();
This method will be exposed to JavaScript script calls
@JavascriptInterface public
void Showlist () {
//Display a normal list dialog box
new Alertdialog.builder (context)
. Settitle ("book list")
. SetIcon (R.mipmap.ic_launcher)
. Setitems (New string[]{"Head of Android", "head of the head of Java", "Thinking in Java"}, NULL)
. Setpositivebutton ("OK", null).
Create ()
. Show ();
}

The MyObject contains two methods, the Showtoast () and the Showlist () methods, and the two methods use the @javascriptinterface adornments, which expose the two methods to JavaScript scripts. This allows JavaScript scripts to invoke both methods through MyObj. The HTML page code is as follows:

<! DOCTYPE html>
 
 

When the user clicks on the two buttons on the page, the JavaScript script for the page invokes the Android method via MyObj.

To run the instance, click the first button and the effect is as follows:

Click on the second button, the effect is as follows:

The above is a small set to introduce the Android WebView application interface Development tutorials, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.