Android WebView Component Usage Summary _android

Source: Internet
Author: User
Tags event listener http request
Browser controls are available in every development environment, which provides a useful place for vest martial, with Windows Webbrowser,android and iOS webview. Unlike its engine, the WebView engine of Microsoft's Webbrowser,android and iOS is WebKit, providing support for HTML5. This article mainly introduces the WebView of Android.

how the WebView component uses
1 Add permissions: Androidmanifest.xml must use the license "Android.permission.INTERNET", otherwise the Web page not available error.
2 Generate a WebView component in the activity: webview WebView = new WebView (this), or you can add a layout control to the activity's WebView file:
Copy Code code 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 accessing, WebView must set up to 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");
Local file use: Webview.loadurl ("file:///android_asset/XX.html"); Local files are stored in the: Assets file.
5 If you want to click on the link by yourself, instead of opening the new Android system browser should be linked in the ring. Add an Event Listener object (webviewclient) to WebView and rewrite some of these methods:
Shouldoverrideurlloading: A response to a hyperlink button in a Web page. When a connection is pressed, Webviewclient calls this method and passes the argument: the pressed URL. For example, when a number in a WebView embedded Web page is clicked, it automatically thinks it is a call request and passes url:tel:123 if you do not want to do so by overriding the Shouldoverrideurlloading function:
Copy Code code as follows:

public boolean shouldoverrideurlloading (webview view,string URL) {
if (Url.indexof ("Tel:") <0) {//The number on the page will cause the connection phone
View.loadurl (URL);
}
return true;
}

There are other ways to rewrite 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);
This function we can do a lot of things, such as we read some special URL, so we can not open the address, cancel this operation, for predefined other operations, which is very necessary for a program.
3, loading the events of the page completion
public void onpagefinished (webview view, String URL) {}
In the same way, we know that a page load is complete, so we can turn off the loading and switch the program action.
4, loading the event at the beginning of the page
public void onpagestarted (webview view, String URL, Bitmap favicon) {}
This event is the start of loading the page call, and usually we can set a loading page here, telling the user that the program is waiting for the network to respond.
Through these events, we can easily control the operation of the program, while using the browser display content, while monitoring the user to achieve the implementation of our needs of various display methods, but also to prevent users from producing misoperation.
6 If you see a lot of pages with a WebView point link, if you do not do any processing, click the System "back" key, the entire browser will call finish () and end itself, if you want to browse the Web page fallback rather than exit the browser, The back event needs to be handled and consumed in the current activity.
Overrides the onkeydown (int keycoder,keyevent event) method of the Activity class.
Copy Code code 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 WebView is returned
return true;
}
return false;
}

WebView and JS Interaction
WebView and JS Two-way interaction is the webview of Android is strong, but also the spirit of the vest can be thoroughly implemented basic protection.
First, WebView can define an event that can be triggered in a nested page within it
Copy Code code 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+"));
}
});
}
}

The above code enables you to trigger the Window.demo.clickOnAndroid (STR) event in the embedded Web page and pass the parameter str to webview. After WebView receives STR, you can use the above code to trigger the JS function Wave (str) in the embedded page. This enables the Web page to trigger WebView events and pass parameters, WebView receive parameters and call the JS function.
Here's a look at my HTML script
Copy Code code 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 Submit to Client"
onclick= "toclient ();" />
<br/>
Display returns: <label id= "fromclient" ></label>
</body>

Using the script to see the Wave (str) function is responsible for the original data passed to WebView back to the page, the effect is as follows:
In addition, if you want to get some processing data for the page and hand it over to the WebView client, you can use the data alert in the wave function, then rewrite the Onjsalert function of webchromeclient in WebView, as follows
Wv.setwebchromeclient (New Mywebchromeclient ());
Copy Code code 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 that you can handle the data in the Android client.
Result.confirm ();
}
return true;
}
Related Article

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.