WebView (Simple browser demo)

Source: Internet
Author: User

In Android apps, web programs need to be parsed using the WebView control, which actually uses the embedded browser of the WebKit kernel.
Here is an example of a simple browser that tells you how to use the WebView:
1 because it involves accessing the network, you must add access to the network permissions in Androidmanifest:

<uses-permission android:name="android.permission.INTERNET" />

2 then in the layout file, add the WebView control.

Because in order to make a browser look, here in addition to add webview, but also added a edittext for the input URL, as well as a button to trigger access to the URL. In addition, four buttons were added to control actions such as "back", "forward", "Home", "set to No graph mode". The detailed code is as follows:

<?xml version= "1.0" encoding= "UTF-8"?><linearlayout  xmlns: Android  = "http://schemas.android.com/apk/res/android"  android:id  =  Android:layout_width  = "fill_parent"  android: Layout_height  = "fill_parent"  android:o Rientation  =;     <linearlayout  android: Layout_width  = "fill_parent"  android:layout_ Height  = "0DP"  android:layout_weight  =< Span class= "Hljs-value" > "1"  android:background  =" #CCCCCC " android:orientation  =" horizontal ";         <edittext  android:id= "@+id/url"  android:layout_width  = "0DP"  android:layout_height  =" wrap_content " android:layout_weight  =" 5 "             android:inputtype  = "Texturi"  android:text  = "www.baidu.com" />         <buttonandroid:id="@+id/visit"android:layout_width="0DP" android:layout_height="Wrap_content"android:layout_weight="1"android: Text="Access" >                                                                    </Button>    </linearlayout>    <progressbar  android:id< /span>= "@+id/loadding_progress"  style  = android: Layout_width  = "fill_parent"  android:layout_ Height  = "12DP"  android:max  =/>     <webview  android:id  = "@+id/wv"  android:layout_width  =< Span class= "Hljs-value" > "fill_parent"  android:layout_height  = "0DP"  android:layout_weight  =" />     <linearlayout  android: Layout_width  = "fill_parent"  android:layout_ Height  = "0DP"  android:layout_weight  =< Span class= "Hljs-value" > "1"  android:background  =" #CCCCCC " android:orientation  =" horizontal ";         <linearlayout  android:la Yout_width  = "0DP"  android:layout_height= "fill_parent"  android:layout_weight  =
      
        "1" 
       android:gravity  = "C Enter ";             <ImageButtonandroid:id="@+id/back"android:layout_width="20DP"  android:layout_height="20DP"android:background="@drawable/backbutton" >                                                                            </ImageButton>        </linearlayout>        <linearlayout  android:la Yout_width  = "0DP"  android:layout_height= "fill_parent"  android:layout_weight  =
      
        "1" 
       android:gravity  = "C Enter ";             <ImageButtonandroid:id="@+id/ahead"android:layout_width="20DP"  android:layout_height="20DP"android:background="@drawable/aheadbutton" >                                                                            </ImageButton>        </linearlayout>        <linearlayout  android:la Yout_width  = "0DP"  android:layout_height= "fill_parent"  android:layout_weight  =
      
        "1" 
       android:gravity  = "C Enter ";             <buttonandroid:id="@+id/home"android:layout_width="20DP" android:layout_height="20DP"android:background="@drawable/homebutton" >                                                                             </Button>        </linearlayout>        <linearlayout  android:la Yout_width  = "0DP"  android:layout_height= "fill_parent"  android:layout_weight  =
      
        "1" 
       android:gravity  = "C Enter ";             <buttonandroid:id="@+id/nopicture"android:layout_width="20DP"  android:layout_height="20DP"android:background="@drawable/wutubutton" >                                                                            </Button>        </linearlayout>    </linearlayout></linearlayout>

3 Next, separate multiple modules to tell the webview of multiple functions.

    • First, be sure to tell how to implement the load page
WebView wv = (WebView) findViewById(R.id.wv);wv.loadUrl("http://www.baidu.com");
    • When loading a page, listen for loading page start, End etc events

This is done by overriding the Webviewclient onpagefinished,onpagestarted method. To complete the action that you want to start and end at the loading page.

 class mywebclient extends webviewclient {@Override Public voidOnpagefinished (WebView view, String URL) {trigger at end of load page        //TODO auto-generated method stub        //You can end the progress bar here        Super. onpagefinished (view, URL); } @Override Public voidOnpagestarted (WebView view, String URL, Bitmap favicon) {//Load trigger at start of page        //TODO auto-generated method stub        //You can start a progress bar here to prompt the user to be loading        Super. onpagestarted (view, URL, favicon); }    }
    • On the previous point, although you can listen to the start and end of the loading page, you cannot know the progress in the loading process. This can be done by overriding the Webchromeclinent onprogresschanged method to know the progress of the loading process.
wv.setWebChromeClient(new WebChromeClient() {publicvoidonProgressChangedint newProgress) {        "加载进度" + newProgress);        loadProgressBar.setProgress(newProgress);        //当进度达到100,则隐藏进度条        if100) {            loadProgressBar.setAlpha(0);        }    }});
    • Using JavaScript in WebView
webSettings = wv.getSettings();     webSettings.setJavaScriptEnabled(true);//设置可以用javaScript
    • Handle the links clicked on the WebView
      When you click a link on WebView, the default behavior is to open it with the default Web browser.
      So if you want to handle the WebView click Link, to provide a webviewclient for your webview, use Setwebviewclient ().
wv.setWebViewClient(new WebViewClient() {    publicbooleanshouldOverrideUrlLoading(final WebView view,final String url) {        wv.loadUrl(url);// 载入网页        returntrue;    }// 重写点击动作,用webview载入});
    • Access History of browsing
      The WebView CanGoBack () method and the CanGoForward () method can be used to determine whether there is a history that can be returned or moved forward.
      If so, the GoBack () method with WebView is used to return or advance through the GoForward method.
case R.id.back:    if (wv.canGoBack()) {        wv.goBack();    }    break;case R.id.ahead:    if (wv.canGoForward()) {        wv.goForward();    }    break;
    • Set No graph mode

This can be achieved by WebSettings's Setblocknetworkimage () method.

wv.getSettings().setBlockNetworkImage(true);
    • Setting up the cache
      Before we talk about setting up caching, let's look at what the cache modes are:
      Load_cache_only: Do not use the network, only read local cache data
      Load_default: Decide whether to fetch data from the network according to Cache-control.
      Deprecated in Load_cache_normal:api level 17, starting from API level 11 with Load_default mode
      Load_no_cache: Do not use caching, only get data from the network.
      Load_cache_else_network, the data in the cache is used whenever there is a local, regardless of whether it expires, or No-cache.

According to the various caching modes explained above, the caching strategy should be to determine if there is a network, if so, use Load_default, no network, use Load_cache_else_network.

Before setting up the cache, you should set a path to the cache and control the cache size:
Setting the cache path can be achieved by WebSettings's Setappcachepath () method;
Setting the cache size can be achieved by WebSettings's Setappcachemaxsize () method.

Then set the cache, you can use the WebSettings setappcacheenabled (true) to achieve;
The key code is:

Set the cache size to WebSettings. setappcacheenabled(true);WebSettings. Setappcachepath(CachePath. GetCachePath());WebSettings. Setappcachemaxsize(1024x768*1024x768*8);When there is a network, the cache mode is set to Load_defaultwhen there is no net, the cache mode is set to Load_cache_else_network;if (checknet. isnetworkconnected()) {websettings. Setcachemode(websettings. LOAD_default);}else {websettings. Setcachemode(websettings. LOAD_cache_else_network);}

WebView (Simple browser demo)

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.