Android WebView Component Usage Summary

Source: Internet
Author: User

Browser controls are available in every development environment, and this gives the vest a place to play, with Windows Webbrowser,android and iOS webview. Just the engine is different, compared to Microsoft's webbrowser,android and iOS WebView engine is WebKit, to support HTML5. This article mainly introduces the WebView of Android.

How WebView components are used
1) Add Permission: Androidmanifest.xml must use the license "Android.permission.INTERNET", otherwise the Web page not available error.
2) Create a WebView component in the activity: WebView WebView = new WebView (this), or you can add a WebView control to the activity's layout file:

The code is as follows:
<webview
Android:id= "@+id/wv"
Android:layout_width= "Fill_parent"
android:layout_height= "Fill_parent"
android:text= "@string/hello"
/>


3) Set WebView basic information:
If you have JavaScript on the page you are visiting, WebView must set up support JavaScript.
Webview.getsettings (). Setjavascriptenabled (True);
Touch Focus Works
Requestfocus ();
Cancel scroll bar
This.setscrollbarstyle (Scrollbars_outside_overlay);
4) Set Wevview to display the page:
Internet use: Webview.loadurl ("http://www.google.com");
For local files: Webview.loadurl ("file:///android_asset/XX.html"); Local files are stored in the: Assets file.
5) If you wish to click on the link handled by yourself instead of the new Android system browser should link. Add an Event Listener object (webviewclient) to WebView and override some of these methods:
Shouldoverrideurlloading: The response to a hyperlink button in a Web page. When a connection is pressed, Webviewclient calls this method and passes the parameter: the URL that is pressed. For example, when a number in a WebView embedded page is clicked, it automatically thinks that this is a call request that will pass url:tel:123 if you do not wish to do so by overriding the Shouldoverrideurlloading function:

The code is as follows:
public boolean shouldoverrideurlloading (WebView view,string URL) {
if (Url.indexof ("Tel:") <0) {//The number on the page will cause the phone to connect
View.loadurl (URL);
}
return true;
}


There are other ways to override it.
1, an event that receives an HTTP request
Onreceivedhttpauthrequest (WebView view, Httpauthhandler handler, string host, String realm)
2, open the event before the link
public boolean shouldoverrideurlloading (WebView view, String URL) {view.loadurl (URL); return true;}
This function we can do a lot of things, such as we read to some special URL, so we can not open the address, cancel the operation, for the pre-defined other operations, which is very necessary for a program.
3. Events loaded on page completion
public void onpagefinished (WebView view, String URL) {}
Similarly, we know that a page loading is complete, so we can close the loading bar, switch the program action.
4, loading the start of the page event
public void onpagestarted (WebView view, String URL, Bitmap favicon) {}
This event is the start of loading the page call, usually we can set a loading in this page, tell the user program is waiting for the network response.
Through these events, we can easily control the operation of the program, while using the browser to display content, while monitoring the user operation to achieve the various display methods we need, but also to prevent the user to create the wrong operation.
6) If you use the WebView point link to see a lot of pages later, if you do not do any processing, click the System "back" button, the entire browser will call finish () and end itself, if you want to browse the page fallback instead of exiting the browser, The back event needs to be processed and consumed in the current activity.
Overrides the onkeydown (int keycoder,keyevent event) method of the Activity class.

The code is as follows:
public boolean onKeyDown (int keycoder,keyevent event) {
if (Webview.cangoback () && Keycoder = = keyevent.keycode_back) {
Webview.goback (); GoBack () indicates that the previous page of the WebView is returned
return true;
}
return false;
}


WebView and JS Interaction
WebView and JS Two-way interaction is the Android WebView strong, but also the vest spirit can be thoroughly implemented basic protection.
First, WebView can define an event that can be triggered in a nested page

The code is as follows:
Wv.addjavascriptinterface (New Demojavascriptinterface (), "demo");
Private Final Class Demojavascriptinterface
{
Demojavascriptinterface () {}
public void Clickonandroid (final String order) {
Mhandler.post (Newrunnable () {
@Override
public void Run () {
jsontext= "{" Name ":" "+order+" "}";
Wv.loadurl ("Javascript:wave (" +jsontext+ ")");
}
});
}
}


With the above code, it is possible to trigger the Window.demo.clickOnAndroid (STR) event in the embedded Web page and pass the parameter str to webview. After WebView receives STR, the above code can trigger the JS function Wave (str) in its embedded page. This enables the Web page to trigger WebView events and pass parameters, WebView receive parameters and invoke the JS function.
Here's a look at my HTML script:

The code is as follows:
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "HTTP://WWW.W3.ORG/TR/HTML4/LOOSE.DTD" >
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 ">
<title>insert title here</title>
<script type= "Text/javascript" src= "Jquery.js" ></script>
<script>
function Toclient ()
{
var order=$ ("#val"). Val ();
Window.demo.clickonAndroid (order);
}
function Wave (str) {
alert (str.name);
$ ("#fromclient"). Text (str.name);
}
</script>
<body> This is an HTML page
<br/>
Enter a string:<br/>
<input id= "Val"/>
<input type= "Submit" value= "click on submission to Client"
Onclick= "Toclient ();" />
<br/>
Show back: <label id= "Fromclient" ></label>
</body>


The script sees that the Wave (str) function is responsible for returning the data originally passed to WebView back to the page, as follows:
In addition, if you want to get some processing data of the page and hand it to the WebView client, you can put the data alert in the wave function, and then rewrite the Onjsalert function of webchromeclient in WebView, the code is as follows
Wv.setwebchromeclient (New Mywebchromeclient ());

The code is as follows:
Final class Mywebchromeclient extends webchromeclient{
@Override
Public Booleanonjsalert (WebView view, string URL, String message, final Jsresult result) {
The message is the alert string in the wave function, so you can manipulate the data in the Android client.
Result.confirm ();
}
return true;
}

Android WebView Component Usage Summary

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.