Android WebView component usage Summary

Source: Internet
Author: User

Browser controls are available in every development environment, which provides a foothold for vest magic. webbrowser for windows, webview for android and ios. However, their engines are different. Compared with Microsoft's webbrowser, android and ios's webview engines are all webkit and provide Html5 support. This article mainly introduces the powerful webview of android.

How to Use webview Components
1) Add permission: The permission "android. permission. INTERNET" must be used in AndroidManifest. xml; otherwise, the Web page not available error may occur.
2) generate a WebView component in the Activity: WebView webView = new WebView (this); or add the webview control to the layout file of the activity:Copy codeThe 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 basic WebView information:
If the accessed page contains Javascript, webview must be set to support Javascript.
Webview. getSettings (). setJavaScriptEnabled (true );
Touch focus Function
RequestFocus ();
Cancel scroll bar
This. setScrollBarStyle (SCROLLBARS_OUTSIDE_OVERLAY );
4) set the web page to be displayed in WevView:
For Internet: webView. loadUrl ("http://www.google.com ");
Use webView. loadUrl ("file: // android_asset/XX.html") to store local files in the assets file.
5) If you want to click the link for processing by yourself, instead of the link in the browser of the new Android system. Add an event listening object (WebViewClient) to WebView and override some of the methods:
ShouldOverrideUrlLoading: Response to the hyperlink button on the webpage. When you press a connection, WebViewClient will call this method and pass the parameter: the url to be pressed. For example, when a number of embedded web pages in webview is clicked, it will automatically consider this as a telephone request and pass the url: tel: 123, if you do not want this, you can rewrite the shouldOverrideUrlLoading function to solve the problem:Copy codeThe Code is as follows: public boolean shouldOverrideUrlLoading (WebView view, String url ){
If (url. indexOf ("tel:") <0) {// a number is displayed on the page, causing a connection call.
View. loadUrl (url );
}
Return true;
}

There are other methods that can be rewritten.
1. Events that receive Http requests
Onmediaedhttpauthrequest (WebView view, HttpAuthHandler handler, String host, String realm)
2. events before the link is opened
Public boolean shouldOverrideUrlLoading (WebView view, String url) {view. loadUrl (url); return true ;}
We can perform many operations on this function. For example, if we read some special URLs, we can cancel the operation without opening the address and perform other pre-defined operations, this is very necessary for a program.
3. Events completed during page loading
Public void onPageFinished (WebView view, String url ){}
Similarly, we know that the loading of a page is complete, so we can close the loading entry and switch the program action.
4. Events that start loading the page
Public void onPageStarted (WebView view, String url, Bitmap favicon ){}
This event is called to load the page. Generally, we can set a loading page here to tell the user program to wait for the network response.
Through these events, we can easily control program operations, while using a browser to display content, while monitoring user operations to achieve the various display modes we need, it can also prevent user misoperation.
6) if you use the webview link to view many pages without any processing, click the system "Back" key and the entire browser will call finish () to end itself, if you want to roll Back the web page instead of exiting the browser, you need to process and consume the Back event in the current Activity.
Override the onKeyDown (int keyCoder, KeyEvent event) method of the Activity class.Copy codeThe 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 webView is returned.
Return true;
}
Return false;
}

Webview and js Interaction
The two-way interaction between Webview and js is the power of android webview, and is also the basic guarantee for the complete implementation of the vest spirit.
First, webview can define an event that can be triggered on its embedded page.Copy codeThe Code is as follows: wv. addJavascriptInterface (new demow.criptinterface (), "demo ");
Private final class demow.criptinterface
{
Demow.criptinterface (){}
Public void clickonAndroid (final String order ){
MHandler. post (newRunnable (){
@ Override
Public void run (){
JsonText = "{" name ":" "+ order + ""}";
Wv. loadUrl ("javascript: wave (" + jsonText + ")");
}
});
}
}

The code above triggers the window. demo. clickOnAndroid (str) event on its embedded webpage and transmits the str parameter to webview. After Webview receives str, it can trigger the js function wave (str) in its embedded page through the above Code ). In this way, webview triggers webview events and transmits parameters. webview receives parameters and calls js functions.
See my Html Script below:Copy codeThe Code is as follows: <! DOCTYPE html PUBLIC "-// W3C // dtd html 4.01 Transitional // EN" "http://www.w3.org/TR/html4/loose.dtd">
<Html>
<Head>
<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>
</Head>
<Body> This is an html page.
<Br/>
Enter a string: <br/>
<Input id = "val"/>
<Input type = "submit" value = "click to submit to client"
Onclick = "toclient ();"/>
<Br/>
Display return: <label id = "fromclient"> </label>
</Body>
</Html>

Through the script, we can see that the wave (str) function is responsible for re-retrieving the data originally transmitted to webview, as shown below:
In addition, if you want to obtain some processing data on the page and hand it over to the webview client for processing, you can use the data alert function in the wave function and then rewrite the onJsAlert function of WebChromeClient in webview. The specific code is as follows:
Wv. setWebChromeClient (new MyWebChromeClient ());Copy codeThe Code is as follows: final class MyWebChromeClient extends WebChromeClient {
@ Override
Public booleanonJsAlert (WebView view, String url, String message, final JsResult result ){
// Message is the alert string in the wave function, so that you can process 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.