This article describes the method of using WebView controls to browse web pages in Android development. Share it for your reference, as follows:
When you encounter mathematical display problems in the project, the regular Textview display cannot process mathematical formulas, and the use of image generation has put a lot of pressure on the server. After querying, you can load JS through webview to implement it. The same method can be implemented in IOS, but the JS rendering efficiency is much higher than that of Android. Make a summary of the Webview.
When using a WebView control, you first need to define a WebView control in the xml layout file. The definition method is as follows:
<WebView android: android:layout_width="match_parent" android:layout_height="match_parent" />
There are many methods provided in WebView, for example, we can usecanGoBack()
Method to determine whether the previous open web page can be returned from the web page;getTitle()
andgetUrl()
Method to obtain the title and URL path of the current web page;loadUrl(String url)
Method loads the web page to be opened, etc. The following code opens the Baidu homepage in the WebView control by using the loadUrl() method.
WebSettings is used to set the properties and state of the WebView. WebSettings and WebView exist in the same life cycle. You can use the following method to obtain the WebSettings object.
WebSettings webSettings = ();
When creating a WebView, the system will make some default settings for the WebView. After we obtain the WebSettings object through the above method, we can take out the default properties and state of the WebView from the WebSettings object. Of course, we can also set the default properties and state of the WebView through the WebSettings object.
Some commonly used methods provided by WebSettings to set the properties and state of WebView are as follows:
(1)setAllowFileAccess(boolean allow);//Set to enable or disable access to file data
(2)setBuiltInZoomControls(boolean enabled);//Set whether zooming 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 to support zoom
WebViewClient is mainly used to assist WebView in handling various notifications, requests and other events. We can use WebViewsetWebViewClient()
Method, specify a WebViewClient for the WebView object. The specific implementation method is as follows:
MyWebViewClient myWebViewClient = new MyWebViewClient(); (myWebViewClient); private class MyWebViewClient extends WebViewClient { //Rewrite the parent class method to make the newly opened web page appear in the current WebView public boolean shouldOverrideUrlLoading(WebView view, String url) { (url); return true; } }
You can see that in the above code, we override the parent class WebViewClient'sshouldOverrideUrlLoading()
Methods enable the newly opened web page to be displayed in the current WebView instead of calling the browser provided by the Android system for access.
There are also many methods provided in WebViewClient, such as the following:
(1)doUpdateVisitedHistory(WebView view, String url, boolean isReload);//Update history
(2)onFormResubmission(WebView view, Message dontResend, Message resend); //Request web page data again
(3)onLoadResource(WebView view, String url);//Load the resources provided by the specified URL
(4)onPageFinished(WebView view, String url);//The web page has been loaded
The JS rendering we do is performed after onpageFinish. The more complex the JS, the slower the rendering.
(5)onPageStarted(WebView view, String url, Bitmap favicon);//The web page starts loading
(6)onReceivedError(WebView view, int errorCode, String description, String failingUrl);//Report error message
It mainly calls to display after the web page fails to load.
WebChromeClient is mainly used to assist WebView in handling Javascript dialog boxes, website icons, website titles, and web page loading progress.
Similarly, we can use the WebViewsetWebChromeClient()
Method, specify a WebChromeClient for the WebView object.
In WebChromeClient, when the loading progress of a web page changes,onProgressChanged(WebView view, int newProgress)
The method will be called; when the icon of the web page changes,onReceivedIcon(WebView view, Bitmap icon)
The method will be called; when the title of the web page changes,onReceivedTitle(WebView view, String title)
The method will be called. Using these methods, we can easily obtain information such as the loading progress of the web page, the title and icon of the web page, as shown in the following code:
MyWebChromeClient myWebChromeClient = new MyWebChromeClient(); (myWebChromeClient); private class MyWebChromeClient extends WebChromeClient { //Get the loading progress of the web page, displayed in the TextView control in the upper right corner public void onProgressChanged(WebView view, int newProgress) { if(newProgress < 100) { String progress = newProgress + "%"; mTextView_progress.setText(progress); } else { mTextView_progress.setText(" "); } } //Get the title of the web page and display it as the title of the application public void onReceivedTitle(WebView view, String title) { (title); } }
With Javascript
Not only can HTML code be run in WebView, but more importantly, WebView can be called with Javascript. In other words, you can get the content of the WebView in Javascript, and at the same time, you can also call the methods in Javascript in WebView.
Let’s talk about how to call the methods in Javascript in WebView.
Here, I used Baidu Maps' API interface (an HTML document with Javascript embedded) and provided the following Javascript method in this interface:
/*********************************/ /* Find location */ /*********************************/ var city = new (map,{renderOptions:{map:map,autoViewport:true}}); function findPlace(place) { (place); }
What we need to do is to call the findPlace() method in the WebView to complete the location search. The method of calling Javascript in WebView is through code("javascript: method name()")To achieve it. The following code obtains the place name the user wants to find from the EditText control, and then calls the JavascriptfindPlace()Method, search.
public void onClick(View view) { switch(()) { case .imagebutton_search: //Find place name String str = mEditText_input.getText().toString(); String url = "javascript:findPlace('" + str + "')"; (url); break; } }
6 Webview loading JS acceleration
public void optimizaWebview() { if (webView != null) { if (.SDK_INT >= 19) { ().setLoadsImagesAutomatically(true); } else { ().setLoadsImagesAutomatically(false); } if (.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { (View.LAYER_TYPE_SOFTWARE, null); } ().setRenderPriority(); ().setBlockNetworkImage(true); ().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); ().setDatabaseEnabled(true); ().setAppCacheEnabled(true); ().setAppCachePath("/data/data//cache"); ().setAppCacheMaxSize(5 * 1024 * 1024); (true); ().setJavaScriptEnabled(true); (new WebChromeClient()); ().setDomStorageEnabled(true); } }
Loading String
(null, (), text/html, UTF-8, null);
webview loading pictures
<img src="imgurl"/>
Load the html under assets
("file:///android_asset/");
For more information about Android related content, please check out the topic of this site:Android View View Tips Summary》、《Android programming activity operation skills summary》、《Android layout layout tips summary》、《Android development introduction and advanced tutorial》、《Android resource operation skills summary"and"Android control usage summary》
I hope this article will be helpful to everyone's Android programming design.