WebView Summary of Usage methods

Source: Internet
Author: User


1, add permissions: Androidmanifest.xml must use the license "Android.permission.INTERNET", otherwise the Web page is not available error.
2. Generate a WebView component in the activity: WebView WebView = new WebView (this);
3, set WebView basic information:
If you have JavaScript on the page you are visiting, WebView must set up support JavaScript.
Webview.getsettings (). Setjavascriptenabled (True);
Touch Focus Works
Requestfocus ();
Cancel scroll bar
This.setscrollbarstyle (Scrollbars_outside_overlay);
4. Set Wevview to display the page:
Internet use: Webview.loadurl ("http://www.google.com");
For local files: Webview.loadurl ("file:///android_asset/XX.html"); Local files are stored in the: Assets file
5. If you want to click on the link handled by yourself, instead of the new Android system browser should link.
Add an Event Listener object (webviewclient) to WebView
And rewrite some of these methods
Shouldoverrideurlloading: The response to a hyperlink button in a Web page.
Webviewclient calls this method when a connection is pressed and passes a parameter: The URL that is pressed
Onloadresource
Onpagestart
Onpagefinish
Onreceiveerror
Onreceivedhttpauthrequest
6, if the WebView point link to see a lot of pages later, if you do not do any processing, click the System "back" button, the entire browser will call finish () and end itself, if you want to browse the page fallback instead of exiting the browser, The back event needs to be processed and consumed in the current activity.
Overrides the onkeydown (int keycoder,keyevent event) method of the Activity class.
[Java] View plaincopyprint?
public boolean onKeyDown (int keycoder,keyevent event) {
if (Webview.cangoback () && Keycoder = = keyevent.keycode_back) {
Webview.goback (); GoBack () indicates that the previous page of the WebView is returned
return true;
}
return false;
}

8,webview.getsettings (). Setjavascriptenabled (true);
Webview.getsettings (). Setjavascriptcanopenwindowsautomatically (True);

9.
* Some properties and states of WebView are set by WebSettings. Obtained through webview.getsettings
Example: setallowfileaccess (access to file data)
Setbuiltinzoomcontrols (sets whether scaling is supported),
Setcachemode (set buffered mode)
Setjavascriptenabled (set whether JavaScript is supported ...).


* Customize the Web browsing program via Webviewclient.      A class that specifically assists WebView in handling various notifications, requests, and so on. Obtained through webview.setwebchromeclient
Method:
Doupdatevisitedhistory (update history)
Onformresubmission (Application re-requesting web page data)
Onloadresource (load resources provided at the specified address)
onpagefinished (Web page loading complete)
onpagestarted (Web page starts loading)
Onreceivederror (report error message)
Onscalechanged (WebView change)
Shouldoverrideurlloading (Control the new connection opens in the current webview)


* Webchromeclient is designed to assist WebView in handling JavaScript dialogs, icons, website titles, loading progress, etc.
Method: Onclosewindow (Close WebView)
Oncreatewindow (Create WebView)
Onjsalert (Handling the Alert dialog box in JS), Onjsconfirm (Handling the Confirm dialog box in JS), onjsprompt (Handling the prompt dialog box in JS)
Onprogresschanged (loading progress bar changed)
Onreceivedicon (page icon change)
Onreceivedtitle (page title change)
Onrequestfocus (WebView display focal length)


Package Com.dan;


Import android.app.Activity;
Import Android.app.AlertDialog;
Import Android.content.DialogInterface;
Import Android.content.DialogInterface.OnClickListener;
Import Android.graphics.Bitmap;
Import Android.os.Bundle;
Import Android.view.View;
Import Android.view.Window;
Import Android.webkit.JsPromptResult;
Import Android.webkit.JsResult;
Import Android.webkit.URLUtil;
Import android.webkit.WebChromeClient;
Import android.webkit.WebSettings;
Import Android.webkit.WebView;
Import android.webkit.WebViewClient;
Import Android.widget.Button;
Import Android.widget.EditText;


public class Webactivity extends Activity {


Private WebView WebView;
Private EditText Urledt;
Private Button btn;

@Override
public void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.web);

Urledt = (EditText) Findviewbyid (r.id.edt_1);
BTN = (Button) Findviewbyid (r.id.btn_1);

WebView = (WebView) Findviewbyid (R.id.web);
WebSettings settings = Webview.getsettings ();
Webview.loadurl ("http://10.0.2.2/affiliate/code/login.php");
Set Support JS script
Settings.setjavascriptenabled (TRUE);
Settings can access files
Settings.setallowfileaccess (TRUE);
Support Scaling
Settings.setbuiltinzoomcontrols (TRUE);
Set Webviewclient
Webview.setwebviewclient (New Webviewclient () {
@Override
public boolean shouldoverrideurlloading (WebView view, String URL) {
View.loadurl (URL);
return true;
}


@Override
public void onpagefinished (WebView view, String URL) {
super.onpagefinished (view, URL);
}


@Override
public void onpagestarted (WebView view, String URL, Bitmap favicon) {
super.onpagestarted (view, URL, favicon);
}

});
Set Webchromeclient
Webview.setwebchromeclient (New Webchromeclient () {


@Override
public boolean Onjsalert (WebView view, string URL, String message,
Jsresult result) {
Alertdialog.builder alert = new Alertdialog.builder (webactivity.this);
Alert.settitle ("Prompt dialog box");
Alert.setmessage (Message). Setpositivebutton ("OK", new Onclicklistener () {
public void OnClick (Dialoginterface dialog, int which) {
}
});
Alert.create (). Show ();
return true;
}


@Override
public boolean onjsconfirm (WebView view, String URL,
String message, jsresult result) {
Return super.onjsconfirm (view, URL, message, result);
}


@Override
public boolean onjsprompt (WebView view, string URL, String message,
String DefaultValue, jspromptresult result) {
Return super.onjsprompt (view, URL, message, defaultvalue, result);
}


@Override
public void onprogresschanged (WebView view, int newprogress) {
WebActivity.this.getWindow (). Setfeatureint (window.feature_progress, newprogress*100);
Super.onprogresschanged (view, newprogress);
}


@Override
public void Onreceivedtitle (WebView view, String title) {
WebActivity.this.setTitle ("China World Trade Union to join the management login page");
Super.onreceivedtitle (view, title);
}

});

Btn.setonclicklistener (New Button.onclicklistener () {
public void OnClick (View v) {
String URL = urledt.gettext (). toString ();
if (Urlutil.isnetworkurl (URL)) {
Webview.loadurl (URL);
}else{
Urledt.sethint ("Input URL error, please re-enter");
}

}
});

}


}
* Back and forward cangoback and CanGoForward
Back off
if ((keycode = = keyevent.keycode_back) && webview.cangoback ()) {
Webview.goback ();
return true;
}


The HTML code is loaded into WebView in the form of a string, and the image resources stored in the device can be referenced in HTML. This method can be very convenient to achieve the Richtextfield effect, especially for some programs to provide some local simple documents, very convenient.


Below is the source code to implement this function:


public void loadhtml () {       final String mimeType = "text/html";        final String encoding = "Utf-8";        final String html = "Webview.setinitialscale (30); This is the point where you can set the scale based on your needs.

WebView Summary of Usage methods

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.