WebView Basic Use

Source: Internet
Author: User

WebViewis a subclass of view that lets you display Web pages in activity.

You can write webview in the layout file: For example, this writes a webview that fills the entire screen: 

<? XML version= "1.0" encoding= "Utf-8"?><WebView  xmlns:android= "http// Schemas.android.com/apk/res/android " android:id=" @+id/webview " android:layout_width=" Fill_ Parent " android:layout_height=" fill_parent "/>        

To load a webpage, use loadUrl() :

WebView Mywebview = (WebView) Findviewbyid (R.id.webview); Mywebview.loadurl (http://www.example.com);

  Note To add permission to access the network in manifest:

<>     <android:name/></manifest>   
set the page webview to display

There are a number of ways to set up Wevview to display pages:

  Internet page directly with: 

Mywebview.loadurl ("http://www.google.com"); 

  For local files:

Mywebview.loadurl ("File:///android_asset/xx.html");   

Local files are stored in the: Assets file.

  you can also load HTML strings directly , such as:

String htmlstring = ";  load this HTML page mywebview.loaddata (htmlstring, "text/html", "Utf-8");  

using JavaScript in WebView

If you want to load a page with JavaScript, you must make JavaScript available for your webview.

Once enabled, you can also create your own interface to interact between your app and JavaScript code.

Enable JavaScript

You can getSettings() do this by getting websettings, and then using setJavaScriptEnabled() enable javascript:

WebView Mywebview = (WebView) Findviewbyid (R.id.webview); WebSettings websettings = mywebview.getsettings (); websettings.setjavascriptenabled (true);  

Many useful settings are available in the websettings.

working with page views

When the user clicks on a link in your webview, the default behavior is that Android launches an app that handles URLs, usually the default browser opens and downloads the destination URL.

However, you can override this behavior in your webview so that the connection is still open in your webview.

Then, depending on the web browsing history maintained in WebView, you can allow users to navigate forward or backward through their pages.

Open all links in WebView

To open a user-clicked link, simply use the Setwebviewclient () method to provide your webview with one WebViewClient such as:

WebView Mywebview = (WebView) Findviewbyid (R.id.webview); Mywebview.setwebviewclient (New Webviewclient ()); 

Right now, you can open the link in your webview.

More control on opening link locations

If you need more control over where to open the link, you can create your own class, inherit WebViewClient it, and then overwrite the shouldOverrideUrlLoading() method.

For example, the following:

    PrivateClass MywebviewclientExtendswebviewclient {@OverridePublicBooleanShouldoverrideurlloading (WebView view, String URL) {
IfUri.Parse(Url).GetHost().equals(www.example.com))
{// This is my web site and so does not override; Let my WebView load // the page return false// Otherwise, the link is not for a page to my site, so launch // Another Activity that handles URLs Intent Intent = new Intent (Intent.action_view, Uri.parse (URL)); startactivity (Intent); return true

The specific link is opened with its own webview, and the other links are in the browser (intent initiates the default activity to process the URL).

After the definition is finished, the object of this class is passed into the Setwebviewclient () method. 

WebView Mywebview = (WebView) Findviewbyid (R.id.webview); Mywebview.setwebviewclient (New Mywebviewclient ()); 

  Practice Validation: When you set Setwebviewclient (new Webviewclient ()) directly, the validation is correct, that is, all links are open in WebView.

When set to a custom Webviewclient subclass object, the discovery link is still open from the default browser.

Browse page history Fallback

When your webview overwrite the URL-loaded behavior, it automatically accumulates a history of pages that you've visited, and you can use goBack() and goForward() approach to move forward or backward through the history.

For example, use the Back button to page back:

    /*** Key response, when viewing the page in WebView, press the Back button when the return to browse history, if not do the whole webview return to exit*/@OverridePublicBoolean OnKeyDown (IntKeyCode, KeyEvent event) {//Check If the key event is the back button and if there's historyif ((keycode = = keyevent.keycode_back) && mywebview.cangoback ()) { // return key returned Mywebview.goback (); return true;} // If It wasn ' t the back key or there's no Web page history, bubble up //to the default // sy Stem behavior (probably exit the activity) return SuperOnKeyDown (KeyCode, event);}   

  The CanGoBack () method returns True when the Web page can be backed back.

Similarly, the CanGoForward () method can check if there is a history that can go forward.

If you do not perform this check, once the GoBack () and goForward() method arrive at the top of the history, they will do nothing.

Without this setting, when the user presses the back key, if the WebView displays the page, the WebView is returned as a whole.

Program Examples

Attach the complete procedure:

ImportAndroid.annotation.SuppressLint;Importandroid.app.Activity;ImportAndroid.content.Intent;ImportAndroid.net.Uri;ImportAndroid.os.Bundle;ImportAndroid.view.KeyEvent;ImportAndroid.view.Menu;ImportAndroid.webkit.WebSettings;ImportAndroid.webkit.WebView;Importandroid.webkit.WebViewClient; @SuppressLint ("setjavascriptenabled"))PublicClass WebactivityExtendsactivity{Private WebView Mywebview =Null; @OverridePublicvoidOnCreate (Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.activity_web);//Open Page Mywebview =(WebView) Findviewbyid (R.id.webview);////Mywebview.loadurl ("http://www.cnblogs.com/mengdd/");//Blog Link mywebview.loadurl ("http://www.baidu.com/");//Baidu Link//JavaScript enable (if you want to load a page with JS code, you have to enable JS) websettings websettings =Mywebview.getsettings (); Websettings.setjavascriptenabled (True);//Open the link in WebView (the default behavior is to use the browser, set this entry with WebView Open)//Mywebview.setwebviewclient (New Webviewclient ());//All links will be opened in the current webview after this setting//Stronger open Link Control: Overwrite a webviewclient class yourself: In addition to specifying a link to open from WebView, the other links open by default mywebview.setwebviewclient (NewMywebviewclient ()); } @OverridePublicBooleanOncreateoptionsmenu (Menu menu) {getmenuinflater (). Inflate (R.menu.activity_web, menu);ReturnTrue; }/*** Custom Webviewclient class, open special link from WebView, other links still open with default browser *@author1 **/PrivateClass MywebviewclientExtendswebviewclient {@OverridePublicBooleanShouldoverrideurlloading (WebView view, String URL) {If(Uri.parse (URL). GetHost (). Equals ("http://www.cnblogs.com/mengdd/archive/2013/02/27/2935811.html") ||Uri.parse (URL). GetHost (). Equals ("http://music.baidu.com/")) {//This is my web site and so does not override; Let my WebView load//The page//This is the official online example, but I click on a specific link is still using the browser instead of my own webview open, plus the following sentence View.loadurl (URL) is still browser, no solution, do not know where the problem//View.loadurl (URL);ReturnFalse; }//Otherwise, the link isn't for a page in my site, so launch//Another Activity that handles URLs Intent Intent =NewIntent (Intent.action_view, Uri.parse (URL)); StartActivity (Intent);ReturnTrue; } }/*** Key response, when viewing the page in WebView, press the Back button when the return to browse history, if not do the whole webview return to exit*/@OverridePublicBoolean OnKeyDown (IntKeyCode, KeyEvent event) {//Check If the key event is the back button and if there's historyif ((keycode = = keyevent.keycode_back) && mywebview.cangoback ()) { // return key returned Mywebview.goback (); return true;} // If It wasn ' t the back key or there's no Web page history, bubble up //to the default // sy Stem behavior (probably exit the activity) return SuperOnKeyDown (KeyCode, event);}}   

References

Because about the web is completely a small white, so others recommend to me a learning site:

http://www.w3school.com.cn/

API guides:building Web Apps in WebView

Http://developer.android.com/guide/webapps/webview.html

Other Learning Links:

Http://www.cnblogs.com/aimeng/archive/2012/05/24/2516547.html

Http://www.apkbus.com/android-44567-1-1.html

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.