WebView usage summary and webview Summary
1. add permissions: The permission "android. permission. INTERNET" must be used in AndroidManifest. xml. Otherwise, the Web page not available error may occur.
2. Generate a WebView component in the Activity: WebView webView = new WebView (this );
3. Set Basic WebView information:
If the accessed page contains Javascript, webview must be set to support Javascript.
Webview. getSettings (). setJavaScriptEnabled (true );
Touch focus Function
RequestFocus ();
Cancel scroll bar
This. setScrollBarStyle (SCROLLBARS_OUTSIDE_OVERLAY );
4. Set the web page to be displayed in WevView:
For Internet: webView. loadUrl ("http://www.google.com ");
Local file: webView. loadUrl ("file: // android_asset/XX.html"); local files are stored in the assets file.
5. If you want to click the link, you can handle it by yourself, instead of clicking the link in the browser of the new Android system.
Add an event listening object (WebViewClient) to WebView)
And rewrite some of the methods.
ShouldOverrideUrlLoading: Response to the hyperlink button on the webpage.
When you press a connection, WebViewClient will call this method and pass the parameter: url
OnLoadResource
OnPageStart
OnPageFinish
OnReceiveError
OnReceivedHttpAuthRequest
6. If you use the webview link to view many pages without any processing, click the system "Back" key and the entire browser will call finish () to end itself, if you want to roll Back the web page instead of exiting the browser, you need to process and consume the Back event in the current Activity.
Override 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 webView is returned.
Return true;
}
Return false;
}
8. webView. getSettings (). setJavaScriptEnabled (true );
WebView. getSettings (). setJavaScriptCanOpenWindowsAutomatically (true );
9,
* Use WebSettings to set some attributes and statuses of WebView. Obtained Through webView. getSettings
Example: setAllowFileAccess (whether file data can be accessed)
SetBuiltInZoomControls (set whether scaling is supported ),
SetCacheMode (set the buffer Mode)
SetJavaScriptEnabled (set whether JavaScript is supported )........
* Use WebViewClient to customize Web browser programs. Classes that assist WebView in handling various notifications, requests, and other events. Obtained Through webView. setWebChromeClient
Method:
DoUpdateVisitedHistory (update History)
OnFormResubmission (the application re-Requests webpage data)
OnLoadResource (load resources provided by the specified address)
OnPageFinished (webpage loaded)
OnPageStarted (webpage loading starts)
OnReceivedError)
OnScaleChanged (WebView changed)
ShouldOverrideUrlLoading (controls the opening of new connections in the current WebView)
* WebChromeClient is used to assist WebView in processing JavaScript dialogs, icons, website titles, loading progress, and so on.
Method: onCloseWindow (disable WebView)
OnCreateWindow (create WebView)
OnJsAlert (processing the Alert dialog box in Js), onJsConfirm (processing the Confirm dialog box in Js), and onJsPrompt (processing the Prompt dialog box in JS)
OnProgressChanged (loading progress bar changed)
OnReceivedIcon (webpage icon change)
OnReceivedTitle (webpage 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 to support Js scripts
Settings. setJavaScriptEnabled (true );
// Set File Access
Settings. setAllowFileAccess (true );
// Supports 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 ("Logon page of China Unicom franchise management ");
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 ("the entered URL is incorrect. Please enter it again ");
}
}
});
}
}
* Backward and forward canGoBack and canGoForward
// Return
If (keyCode = KeyEvent. KEYCODE_BACK) & webView. canGoBack ()){
WebView. goBack ();
Return true;
}
Load Html code to WebView in the form of a String, and reference the image resources stored in the device in Html. This method is very convenient to achieve the effect of RichTextField, especially when some simple local documents are provided for some programs.
Below is the source code for implementing this function:
Public void loadHTML () {final String mimeType = "text/html"; final String encoding = "UTF-8 "; final String html = "WebView. setInitialScale (30); // This is the focus. You can set the scaling ratio here as needed.
Android: how to find content on the page displayed by WebView
It is mainly designed to display html files. Because of this, during application development, we can organize the content to be displayed into a String in html format to easily achieve various typographical effects.
Although the WebView component encapsulates many functions to facilitate application development, but due to its limited open methods, sometimes this convenience may cause great constraints to developers, for example, developers cannot easily control the start line of WebView display and cannot obtain related row information. Therefore, when WebView is convenient to the public, there will inevitably be many shortcomings.
In the process of application development, the widowed person encountered a problem: displaying the specified content in html to the current screen. How can this problem be solved? The WebView open method has never been well studied over and over again. If we can't do it in the white road, we will go to the black road. If we can't do it in the history, we will collect the wild history. What's the so-called Great road to Rome! As a result, few people search for the source code of WebView everywhere, hoping to improve through unconventional methods (calling methods not open in the WebView class library. But it is very difficult. It is also obvious that, even if it is found, it is not a secure call. This is like a reverse building in Shanghai. Maybe it will be flat at any time. This road is not only bumpy, but has a bright future, and may be broken.
Heaven! Even though it is expensive, it is sometimes helpless. What should I do? Once again, I looked at the poor methods WebView opened. Finally, I thought about findAll and findNext. As a result, I thought, if we can ensure the uniqueness of the content to be located and search for the content to be located, will this content not be displayed on the current screen? As a result, we were very unhappy and planned to give it a try. After the success, the whole country celebrated.
However, when I look at the help document, the two methods are empty, so I feel a little uneasy. Sure enough, there is no effect in the program. Few people had to consult Baidu and Google, the two government ministers of China and the West. Finally, we have an answer. Next, let's look at the world. You have listened carefully:
First, let's look at the remarks from the Assistant Minister to Jack:
Find is not a fully supported feature in webview.
However, try calling view. setFindIsUp (true) to get the match to draw; This function is den and subject to change, so your app may break in a future release. webView does not fully support the search function. However, we can try to call
SetFindIsUp
Method to obtain the query result, and display it on the current screen (painted ). This method is hidden and prone to changes, so your application may not be able to use it normally in future versions.
It can be seen that to use findAll and findNext, you must call
SetFindIsUp
Method, but this method is an internal function, so security cannot be guaranteed, and may be harmonious in a future version.
However, this is the only secure solution. If it cannot be used normally in a later version, it may be better to support WebView! Example: Assume that WebView has html content loaded. The following is a program for searching:
WebView webView = (WebView) findViewById (R. id. webView );
WebView. findAll (a); try {Method m = WebView. class. getMethod (setFindIsUp, Boolean. TYPE );
M. invoke (webView, true );
} The same applies to catch (Throwable ignored) {} findNext. Conclusion: findAll & find... of lWebView>
Webview: Select whether to use the local browser to open
1. generally, you may want to use WebView to open the internal link of a Web page instead of calling a mobile browser. We can use either of the following two methods: (1) set a WebViewClient for WebView, and override the shouldOverrideUrlLoading (WebView view, String url) method. ClassMyWebViewClientextendsWebViewClient {@ OverridepublicbooleanshouldOverrideUrlLoading. loadUrl (url); returntrue ;}} (2) sets a WebViewClient for WebView and overrides the onPageStarted (WebView view, String url, Bitmap favicon) method. Other {@ OverridepublicvoidonPageStarted (WebViewview, Stringurl, Bitmapfavicon) {// TODOAuto-generatedmethodstubsuper.onPageStarted (view, url, favicon);} both methods actually make the parameter view (WebView) loading the parameter url to avoid loading the url by the mobile browser. The first method is more commonly used. 2. However, in some cases, we may want to use WebView to open most of the links, while in some cases, we want to call a mobile browser to open them. This is the case in a recent project. This is actually very simple. We only need to modify the first method above. ClassMyWebViewClientextendsWebViewClient {@ brief (WebViewview, Stringurl) {// rewrite this method to indicate that clicking the link in the webpage is still redirected to the current webview, without skipping to the browser if (openWithWevView (url )) {view. loadUrl (url);} else {Uriuri = Uri. parse (url); // url startActivity (intent);} returntrue;} Where openWithWevView (url) is a self-written method, used to determine whether to use WevView to open the link.