Android--webview Nested Web pages

Source: Internet
Author: User

WebView Nested Web pages

For some reason, we always need to show some complex text, html.fromhtml () can not meet our needs, such as the background editable text in front of the display is more difficult, so in order to solve some complex text display needs to use the webview.

Developed through mobile development platforms such as PHONGGAP or ExtJS jquery mobile, etc.
The idea is to use a HTML5-developed program to package the platform into apk iOS Winphone and so on through various platforms.

WebView mainly calls three methods: Loadurl, LoadData, Loaddatawithbaseurl.
1, Loadurl directly load the webpage, the picture and displays. (Local or Web pages, pictures, gifs)
2, LoadData display text and picture content (simulator 1.5, 1.6)
3, Loaddatawithbase display text and picture content (support multiple emulator versions)

1.WebView

When using the WebView control, you first need to define a WebView control in the XML layout file, defined by the following methods:

This is a network privilege.

< WebView     Android:id = "@+id/webview" Android:layout_width = "Match_parent" Android:layout_height = "Match_parent" />

(1) Angoback () to determine whether the page can be returned from the previous open page ;

(2) GetTitle (), GETURL () gets the title and URL path of the current page

(3) loadurl (String URL) loads the Web page you want to open, and so on. The following code opens the Baidu home page in the WebView control by using the Loadurl () method.

    Private WebView Mwebview;     = (WebView)this. Findviewbyid (R.id.webview);    Mwebview. Loadurl ("http://www.baidu.com/");

2.WebSettings

The websettings is used to set the properties and state of the WebView. WebSettings and WebView exist in the same life cycle, you can obtain WebSettings objects using the following methods

WebSettings websettings = Mwebview.getsettings ();

When creating the WebView, the system will make some default settings for WebView, and when we get the WebSettings object from the above method, we can remove and set it from the WebSettings object. Properties and states of the WebView

WebSettings provides some common ways to set the properties and state of WebView as follows:

(1) setallowfileaccess (Boolean allow); Set enable or disable access to file data

(2) Setbuiltinzoomcontrols (Boolean enabled); Set whether scaling is supported

(3) setdefaultfontsize (int size); Set the default font size

(4) setjavascriptenabled (Boolean flag); Set whether JavaScript is supported

(5) Setsupportzoom (Boolean support); Set whether Zoom is supported

3.WebViewClient

Webviewclient is mainly used to assist WebView to handle various notifications, requests and other events. This allows the newly opened Web page to be displayed in the current WebView, rather than being accessed by invoking the browser that comes with the Android system.

        Webview.setwebviewclient (new  webviewclient () {            publicboolean  Shouldoverrideurlloading (WebView view, String URL) {                view.loadurl (URL);                 // If True is turned on with WebView, the system browser or third-party browser is called false.                 returntrue;            }        });

We can specify a webviewclient for the WebView object through the WebView setwebviewclient () method.

 mywebviewclient mywebviewclient =  Mywe        Bviewclient ();        Mwebview.setwebviewclient (mywebviewclient);  private  class  mywebviewclient Span style= "color: #0000ff;" >extends   Webviewclient { // 
   
     Override the parent class method to have the newly opened Web page display the  
    public  
    boolean  
     Shouldoverrideurlloading (WebView view, String URL) {View.loa                Durl (URL);  
    return  
    true  
    ; }        }
   

As you can see, in the code above, we override the Shouldoverrideurlloading () method of the parent class webviewclient in the subclass Mywebviewclient,

There are also a number of ways to do this in webviewclient, such as the following:

(1) doupdatevisitedhistory (WebView view, String URL, boolean isreload); Update history

(2) onformresubmission (WebView view, message dontresend, message resend); Re-request Web page data

(3) Onloadresource (WebView view, String URL); Load the resources provided by the specified URL

(4) onpagefinished (WebView view, String URL); Page loading complete

(5) onpagestarted (WebView view, String URL, Bitmap favicon); Web page starts loading

(6) Onreceivederror (WebView view, int errorCode, string description, String failingurl); Reporting error messages

4.WebChromeClient

Webchromeclient is mainly used to assist WebView in the processing of JavaScript dialog boxes, website icons, site titles, and page loading progress .

Similarly, we can specify a webchromeclient for the WebView object through the WebView setwebchromeclient() method.

In the Webchromeclient,

The onprogresschanged (WebView view, int newprogress) method is called when the page's loading progress is changed ;

The Onreceivedicon (WebView view, Bitmap icon) method is called when the icon of the page changes ;

The Onreceivedtitle (WebView view, String title) method is called when the title of the page changes .

With these methods, we can easily get information such as the loading progress of the Web page, the title of the page, and the icon, as shown in the following code:

Mywebchromeclient mywebchromeclient =Newmywebchromeclient ();        Mwebview.setwebchromeclient (mywebchromeclient); Private classMywebchromeclientextendswebchromeclient {//get the page loading progress, displayed in the TextView control in the upper-right corner             Public voidOnprogresschanged (WebView view,intnewprogress) {                if(Newprogress < 100) {String Progress= newprogress + "%";                Mtextview_progress.settext (progress); } Else{Mtextview_progress.settext (" "); }            }            //get the title of the page and display it as the title of the application             Public voidOnreceivedtitle (WebView view, String title) {mainactivity. This. Settitle (title); }        }

5.WebView and JavaScript

Not only can you run HTML code in WebView, but more importantly, WebView can call each other with JavaScript. In other words, you can get WebView content in JavaScript, and in the meantime, you can call the JavaScript method in WebView.

Here's how to invoke JavaScript in WebView.

Here, I use the Baidu Map API interface (a JavaScript-embedded HTML document), which provides the following JavaScript methods:

     /* ******************************* */     /*            Find a            place */     *********************************     / var New Bmap.localsearch (map,{renderoptions:{map:map,autoviewport:true});              function findplace (place)     {         City.search (place); }

All we have to do is call the Findplace () method in the WebView to complete the location lookup. The method of invoking JavaScript in WebView is implemented by code Webview.loadurl ("javascript: Method Name ()"). The following code, from the EditText control, gets the place name that the user wants to find, and then calls the Findplace () method in JavaScript to find it.

      Public void OnClick (view view) {         switch(View.getid ()) {         case r.id.imagebutton_ Search:                    // Find place name             String str = medittext_input.gettext (). toString ()             ; = "Javascript:findplace ('" + str + "')";             Mwebview.loadurl (URL);               Break ;         }     }

For example, we look for "Yuanmingyuan" to see the results shown in 2.

WebView in ScrollView

We all know that ScrollView and WebView have a scrolling effect, so we need to block WebView's scrolling events first .

< ScrollView     Android:layout_width = "Match_parent"     android:layout_height= "Wrap_content"    android:descendantfocusability = "Blocksdescendants" >
Chinese garbled

If there is a garbled Chinese, you can set this

Webview.loaddata (Body, "text/html; Charset=utf-8 "," utf-8 ");

Auto Scale

At this point, if the backend is not full HTML, but only the body part of the content, then we need to add some CSS style to achieve the adaptive effect.

New WebView (this); Webview.setwebviewclient (new  simplewebviewclient (title));        Webview.getsettings (). Setdefaulttextencodingname ("Utf-8"); if (Build.VERSION.SDK_INT >= build.version_codes. KITKAT) {    else  {     "text/html; Charset=utf-8", "utf-8");

Don't forget the setting of the head:

Private string Gethtmldata (String bodyhtml) {    = ";     return ";}

How to control the height of WebView, unexpectedly webview can adapt to the content of the longest height.

Android--webview Nested Web pages

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.