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:

<manifest >     <uses-permission android:name= "Android.permission.INTERNET"/>     ... </ 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 = "

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:

    Private class Mywebviewclient extends Webviewclient    {        @Override public        boolean shouldoverrideurlloading ( WebView view, String URL)        {
if (Uri. Parse(URL). GetHost(). equals(www.example.com))
{//This was my web site, so does not override; let my WebView load//the page return false;} Otherwise, the link isn't for a page in my site, so launch//another Activity that handles URLs Intent Intent = new I Ntent (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:

    /**     * button response, when viewing the page in WebView, press the Back button when the return by browsing history, if you do not do this processing, the entire webview return to exit     */    @Override public    Boolean OnKeyDown (int keycode, keyevent event)    {        //Check If the key event is the back button and if there ' s        history if ((keycode = = keyevent.keycode_back) && mywebview.cangoback ())        {            //Return key return            mywebview.goback ();            return true;        }        If It wasn ' t the back key or there's no Web page history, bubble up        //to the default        //system behavior (pro Bably exit the activity)        return Super.onkeydown (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:

1 WebView Basic2 3 ImportAndroid.annotation.SuppressLint;4 Importandroid.app.Activity;5 Importandroid.content.Intent;6 ImportAndroid.net.Uri;7 ImportAndroid.os.Bundle;8 Importandroid.view.KeyEvent;9 ImportAndroid.view.Menu;Ten Importandroid.webkit.WebSettings; One ImportAndroid.webkit.WebView; A Importandroid.webkit.WebViewClient; -  -@SuppressLint ("setjavascriptenabled") the  Public classWebactivityextendsActivity - { -     PrivateWebView Mywebview =NULL; -  + @Override -      Public voidonCreate (Bundle savedinstancestate) +     { A         Super. OnCreate (savedinstancestate); at Setcontentview (r.layout.activity_web); -  -         //Open Web page -Mywebview =(WebView) Findviewbyid (R.id.webview); -         // -  in         //Mywebview.loadurl ("http://www.cnblogs.com/mengdd/");//Blog Links -Mywebview.loadurl ("http://www.baidu.com/");//Baidu Link to  +         //JavaScript Enable (if there is JS code in the page to be loaded, JS must be enabled) -WebSettings websettings =mywebview.getsettings (); theWebsettings.setjavascriptenabled (true); *  $         //Open the link in WebView (the default behavior is to use the browser, set this entry with WebView Open)Panax Notoginseng         //mywebview.setwebviewclient (New Webviewclient ()); -         //all links will be opened in the current webview after this setting the  +         //Stronger Open Link control: Overwrite a webviewclient class yourself: Except for the specified link from WebView Open, the other links are open by default AMywebview.setwebviewclient (Newmywebviewclient ()); the  +     } -  $ @Override $      Public BooleanOncreateoptionsmenu (Menu menu) -     { - getmenuinflater (). Inflate (R.menu.activity_web, menu); the         return true; -     }Wuyi  the     /** - * Custom Webviewclient class, open special links from WebView, other links still open with default browser Wu      *  -      * @author1 About      *  $      */ -     Private classMywebviewclientextendswebviewclient -     { - @Override A          Public Booleanshouldoverrideurlloading (WebView view, String URL) +         { the             if(uri.parse (URL) - . GetHost () $. Equals ("http://www.cnblogs.com/mengdd/archive/2013/02/27/2935811.html") the||uri.parse (URL). GetHost () the. Equals ("http://music.baidu.com/")) the             { the                 //This is my web site and so does not override; Let my WebView load -                 //The page in  the                 //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 the                 //view.loadurl (URL); About                 return false; the             } the             //Otherwise, the link isn't for a page in my site, so launch the             //another Activity that handles URLs +Intent Intent =NewIntent (Intent.action_view, Uri.parse (URL)); - startactivity (intent); the             return true;Bayi         } the     } the  -     /** - * 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 the      */ the @Override the      Public BooleanOnKeyDown (intKeyCode, keyevent event) the     { -         //Check If the key event is the back button and if there's history the         if((keycode = = Keyevent.keycode_back) &&mywebview.cangoback ()) the         { the             //return key Bounce94 Mywebview.goback (); the             return true; the         } the         //If It wasn ' t the back key or there's no Web page history, bubble up98         //To the default About         //system behavior (probably exit the activity) -         return Super. OnKeyDown (KeyCode, event);101     }102 103}

Resources

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

From: http://www.cnblogs.com/mengdd/archive/2013/03/01/2938295.html

WebView Basic Use

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.