Overview:
A view that displays the Web page. This class is the basis for scrolling through your Web browser or simply displaying some online content in your activity. It uses the WebKit rendering engine to display Web pages, including methods for forward and backward navigation (through history), zooming in and out, performing text searches, and so on.
Note that in order for your application to be able to use WebView to access the Internet and load Web pages, you must add Internet permissions to the android manifest file:
<uses-permission android:name= "Android.permission.INTERNET"/>
Class Structure:
Java.lang.Object
↳android.view.view
↳android.view.viewgroup
↳android.widget.absolutelayout
↳ Android.webkit.WebView
Common methods:
WebSettings
|
GetSettings ()
Gets the WebSettings object that sets the WebView.
|
void
|
Setwebviewclient (webviewclient client)
Sets the webviewclient that will receive various notifications and requests.
|
void
|
Setwebchromeclient (webchromeclient client)
Set up chrome processing.
|
Description
WebSettings getsettings () Gets the WebSettings object that sets the WebView.
WebSettings Common methods:
Method
|
Description
|
Setallowfileaccess
|
Enable or disable WebView access to file data
|
Setblocknetworkimage
|
Whether to display network images
|
Setbuiltinzoomcontrols
|
Set whether scaling is supported
|
Setcachemode
|
Set the mode of buffering
|
Setdefaultfontsize
|
Set the default font size
|
Setdefaulttextencodingname
|
Set the default encoding to use when decoding
|
Setfixedfontfamily
|
To set a fixed-use font
|
Setjavascriptenabled
|
Setting whether JavaScript is supported
|
Setlayoutalgorithm
|
Set layout style
|
Setlighttouchenabled
|
To set the option to activate with the mouse
|
Setsupportzoom
|
Set whether Zoom is supported
|
void Setwebviewclient (Webviewclient client)
Sets the webviewclient that will receive various notifications and requests.
Webviewclient Common methods:
Method
|
Description
|
Doupdatevisitedhistory
|
Update history
|
Onformresubmission
|
Application requests Web page data again
|
Onloadresource
|
Load the resource provided by the specified address
|
Onpagefinished
|
Web page Loading complete
|
onpagestarted
|
Web page starts loading
|
Onreceivederror
|
Reporting error messages
|
Onscalechanged
|
WebView has changed.
|
Shouldoverrideurlloading
|
Controls the new connection to open in the current WebView
|
void Setwebchromeclient (Webchromeclient client) sets Chrome processing.
Webchromeclient Common methods:
Method
|
Description
|
Onclosewindow
|
Close WebView
|
Oncreatewindow
|
Create WebView
|
Onjsalert
|
Working with the Alert dialog box in JavaScript
|
Onjsconfirm
|
Working with the Confirm dialog box in JavaScript
|
Onjsprompt
|
Working with the prompt dialog box in JavaScript
|
Onprogresschanged
|
Load progress bar Changes
|
Onreceivedlcon
|
Web page icon Changes
|
Onreceivedtitle
|
Page title change
|
Onrequestfocus WebView
|
Show Focus
|
Custom WebView, you can add your own behavior:
Create and set webchromeclient subclasses. This class is invoked when some user interfaces that may affect the browser occur, such as progress updates and JavaScript alerts sent here (see Debug Tasks). The
creates and sets the Webviewclient subclass. When the effect of content rendering occurs is calling this class, for example, error or form submission. You can also intercept the URL loaded here (via Shouldoverrideurlloading ()).
Modify websettings, such as enabling JavaScript in setjavascriptenabled () mode. The
injects Java objects through the Addjavascriptinterface (object,string) method to WebView. This approach allows you to inject Java objects into the JavaScript context of a page so that they can access pages through JavaScript.
The following is a more complex example, showing error handling, setting, and progress notification:
/Let's display the progress in the activity title bar, like the//browser appdoes.
GetWindow (). Requestfeature (window.feature_progress);
Webview.getsettings (). Setjavascriptenabled (True);
Final activity activity = this; Webview.setwebchromeclient (New Webchromeclient () {public void onprogresschanged (WebView view, int progress) {//acti
Vities and Webviews measure progress with different scales.
The progress meter would automatically disappear when we reach 100% activity.setprogress (progress * 1000);
}
}); Webview.setwebviewclient (New Webviewclient () {public void Onreceivederror (webview view, int errorcode, String descripti
On, String Failingurl} {toast.maketext (activity, "Oh no!" + description, Toast.length_short). Show ();
}
});
Webview.loadurl ("http://developer.android.com/");
Scaling:
You can enable built-in scaling by setting Websettings.setbuiltinzoomcontrols (Boolean).
Note: Using scaling, if not the height or width set to wrap_content may result in an indeterminate behavior and should be avoided.
Cookies and Window management:
For obvious security reasons, your application has its own cache, cookie storage, and so on, and it does not share data from browser applications.
By default, opening a new window through an HTML request is ignored. This is exactly whether they are opened by JavaScript or by the target link. You can customize your webchromeclient to provide your own behavior by opening multiple windows and using any way you want to render them.
Building a Web application in WebView:
If you want to provide a Web application (or just a Web page) as part of the client application, you can use WebView to do this. The WebView class is an extension of the Android view class, which allows you to display pages as part of your active layout. It does not include any features of a fully developed web browser, such as a navigation control or an address bar. All WebView By default is to display a Web page.
A common scenario for using WebView: It's helpful to use WebView when you want to provide information that might need to be updated in your application, such as an end user protocol or user guide. In your Android app you can create an online hosted document that contains WebView activity and then uses it to display.
Another common scenario that uses WebView is that if your application provides data that always needs to be retrieved from the Internet, such as e-mail. In this case, you may find it easier to display all the user data in your Android app, instead of executing a Web request, then parsing the data and rendering it in Android layout to build a webview. Instead, you can design a Web page designed specifically for Android devices and then implement the WebView on your Android app load.
Here's how you can start using WebView and how to do something extra, such as working with page navigation in your Android application and binding JavaScript to client code from a Web page.
Basic usage:
By default, WebView does not provide browser-like widgets, and JavaScript and Web page errors are ignored. If your goal is to show some HTML as part of the user interface, this may be fine; the user will no longer need to interact with the Web page, and the page will not need to interact with the user. If you need a comprehensive web browser, you may want to invoke the browser application to load the URL instead of displaying it in WebView. For example:
1 Add a WebView to your app:
<?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 "
/>
2 Use the Loadurl () method to load a Web page:
WebView Mywebview = (webview) Findviewbyid (R.id.webview);
Mywebview.loadurl ("http://www.example.com");
3 to add access to the network to the application:
<manifest >
<uses-permission android:name= "Android.permission.INTERNET"/>
</manifest >
The above is all the steps to display a basic Web page.
Using JavaScript in WebView:
If you plan to use JavaScript when your WebView loads Web pages, you must enable JavaScript for your webview. Once JavaScript is enabled, you can also create an interface between your application code and JavaScript code.
JavaScript is disabled by default in WebView. You can enable it by attaching the websettings on the webview. Even if you get websettings with GetSettings (), then enable JavaScript using the Setjavascriptenabled () method.
WebView Mywebview = (webview) Findviewbyid (R.id.webview);
WebSettings websettings = Mywebview.getsettings ();
Websettings.setjavascriptenabled (TRUE);
JavaScript code is bound to the Android code:
In developing a Web application, specifically designed for WebView in your Android application, you can create interfaces between your JavaScript code and the client's Android code. For example, your JavaScript code can call a method in your Android code to display dialog instead of using the Javascriptalert () method.
Call the Addjavascriptinterface () method to bind the interface between a new JavaScript and the Android code. It is bound to your javascrip,javascript by a class instance that can call an interface name to access the class.
public class Webappinterface {context
mcontext;
/** Instantiatethe interface and set the context * *
webappinterface (context c) {
mcontext = c;
}
/** show a Toastfrom the Web page *
/@JavascriptInterface public
void Showtoast (String toast) {
Toast.maketex T (Mcontext, Toast, Toast.length_short). Show ();
}
Note: If you set the Targetsdkversion to 17 or higher, you must add @javascriptinterface to add annotations for any JavaScript that you want to provide to you (the method must be public). If you do not provide annotations, the method is not accessible to Web pages when running on Android4.2 or later.
In the above example, the Webappinterface class allows the Web page to invoke the Showtoast () method to create a toast message.
You can bind this class to JavaScript running in your WebView by using the Addjavascriptinterface () method and the Android interface name.
WebView WebView = (webview) Findviewbyid (R.id.webview);
This will create an interface called Android for JavaScript running in WebView. At this point, the Web application can access the Webappinterface class. For example, here are some HTML and JavaScript that will create a toast message when the button is clicked.
<input type= "button" value= "SayHello" onclick= "Showandroidtoast" (' Hello android! ') "/> <script type=
" Text/javascript ">
function Showandroidtoast (toast) {
android.showtoast (toast);
}
</script>
This does not require the initialization of Android from the JavaScript interface. WebView automatically applies it to your Web page. Therefore, press the button Showandroidtoast () method to invoke the Webappinterface.showtoast () method using the Android interface.
Note: Bind to your JavaScript object to run on another thread rather than the thread it builds on.
Warning: Using Addjavascriptinterface () will allow JavaScript to control your Android application. This is a very useful feature or a dangerous security issue. When WebView HTML is not trustworthy (for example, some or all of the HTML is provided by an unknown person or process), then the attacker executes any client code included in the HTML and selection. Therefore, you should not use Addjavascriptinterface () unless you write all HTML and JavaScript appear in your webview. You should also not allow users to navigate to other pages that are not their own, within your webview (instead, allow the user to open external links via the default browser application). The application Web browser opens all URL links, so be careful that you only describe the following sections in the Process page navigation.
Working with page navigation:
When a user clicks a link on a webview, the default behavior is to start an Android application that handles URLs. Usually the default Web browser opens and is installed at the destination URL. But you can cover this behavior for WebView to open the link on your webview. You can then allow users to browse through the history of the pages that are retained by your webview.
To open the user click Link, simply provide a webviewclient for your webview, using setwebviewclient ().
WebView Mywebview = (webview) Findviewbyid (R.id.webview);
Mywebview.setwebviewclient (New Webviewclient ());
Such All the links that the user clicks on are loaded on your webview.
If you want more control click on the link load, create your own webviewclient overlay shouldoverrideurlloading () method.
Private class Mywebviewclient extends Webviewclient {
@Override public
boolean shouldoverrideurlloading ( WebView view, String URL) {
if (uri.parse (URL). GetHost (). Equals ("www.example.com")) {
//This are my web site, so D o not override;let me webview load the page return
false;
}
Otherwise, the link isn't to a page on my site, so launch anotheractivity that handles URL
Intent = new I Ntent (Intent.action_view, Uri.parse (URL));
StartActivity (intent);
return true;
}
Then create a new Webviewclient instance for WebView:
WebView Mywebview = (webview) Findviewbyid (R.id.webview);
Mywebview.setwebviewclient (New Mywebviewclient ());
Now, when the user clicks on a link, the system calls Shouldoverrideurlloading (), which checks to see if the URL host matches a specific domain (as defined above). If it does not, the method returns false in order to load the URL that does not rewrite (it allows WebView to load URLs as usual). If the host in the URL does not match, then a intent will be created to initiate the default activity processing url (which resolves the user's default Web browser).
History of browsing Web pages:
When your webview overloaded URLs are loaded, WebView automatically sums up the history of the pages you visit. You can navigate backwards and forwards through the GoBack () and GoForward () methods.
@Override Public
boolean onKeyDown (int keycode, keyevent event) {
//Check If Thekey event is the back button and If there ' s history
if (keycode = = keyevent.keycode_back) && mywebview.cangoback ()) {
Mywebview.goback ();
return true;
}
If it wasn ' tthe back key or there ' No. Web page history, bubble up to the default
//Systembehavior (probably exit The activity) return
Super.onkeydown (KeyCode, event);
}
If there is an actual page history user accesses the CanGoBack () method returns True. Similarly, you can use CanGoForward () to check whether there is a historical advance. If you do not perform this check, GoBack () or GoForward () does nothing once the user arrives at the end of history.