Android WebView: androidwebview

Source: Internet
Author: User

Android WebView: androidwebview

WebView is a control used in Android to display html text content. It also has good support for html5. the ios control is similar to UIWebView. There are many interpretations of WebView on the Internet, but they are all sporadic introductions. As a result, webview has given me an impression so far. It seems very powerful, but it is actually very weak, so I decided to summarize the development experience of webview.

You do not need to activate network permissions to use WebView.

There is an article on the internet saying that webview requires internet permission; otherwise, the Web page not available error may occur. This is not true. The Web page not available does not use webview, but webview accesses the network, if webview only loads local html (such as files in the assets Directory) or loads strings containing html text, no error is reported even if you do not have internet permissions.

How to call webview

In xml

12345 <WebView    android:id="@+id/blog_detail_webview"    android:layout_width="fill_parent"    android:layout_height="wrap_content"    android:background="#FFFFFF"/>

Activity

123456 mWebView = (WebView)findViewById(R.id.blog_detail_webview);mWebView.getSettings().setJavaScriptEnabled(false);mWebView.getSettings().setSupportZoom(false);mWebView.getSettings().setBuiltInZoomControls(false);mWebView.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);mWebView.getSettings().setDefaultFontSize(18);

Basic settings

The java code above is understandable. We can see that WebView is different from other controls in that its property setting is to call mWebView. getSettings () to complete, do not know the intention of Google's design, of which:

MWebView. getSettings (). setJavaScriptEnabled (false );

It indicates that js is not supported. If you want java to interact with js or want js to complete some functions, change false to true.

MWebView. getSettings (). setsuppzoom zoom (false );

Set whether scaling is supported. Here, it is false. The default value is true.

MWebView. getSettings (). setBuiltInZoomControls (false );

Sets whether to display the Zoom tool. The default value is false.

MWebView. getSettings (). setLayoutAlgorithm (LayoutAlgorithm. SINGLE_COLUMN );

This is rarely used. When a common web page is displayed using the WebView component, a horizontal scroll bar is usually displayed, which makes it very inconvenient to view the page. LayoutAlgorithm is an enumeration used to control the html layout. There are three types in total:
NORMAL: NORMAL display, no rendering changes.
SINGLE_COLUMN: Place all content in the same width column of the WebView component.
NARROW_COLUMNS: if possible, the width of all columns cannot exceed the screen width.

MWebView. getSettings (). setDefaultFontSize (18 );

Set the default font size. The default value is 16 and the valid value range is between 1 and 72.

Load content

(1) load the local webpage under the assets Directory

Generally, we place html files in the assets Directory. WebView is very convenient to call local webpages, images, and other resources under the assets Directory.

1 mWebView.loadUrl("file:///android_asset/html/test1.html");

.

(2) Loading remote web pages

1 mWebView.loadUrl("http://www.google.com");

(3) Use LoadData or loadDataWithBaseURL to load content

Sometimes our webview may be just an html clip, rather than a complete webpage. In fact, most of the time, the complete webpage does not need to be made into an application, but is directly accessed in a browser.

In this case, we use the LoadData or loadDataWithBaseURL method, which is the most used:

Void loadDataWithBaseURL (String baseUrl, String data, String mimeType, String encoding, String historyUrl)

LoadDataWithBaseURL () has two more parameters than loadData (). You can specify the relative root path of the resources in the HTML code snippet, or specify the historical Url. The remaining three parameters are the same.

Here, pay attention to the baseUrl parameter. baseUrl specifies the data address in your data parameter as the benchmark, because data in data may have hyperlinks or image elements, many websites use relative paths. Without baseUrl, webview cannot access these resources.

For example:

12 String body ="Example: Here is an img tag with the relative path ;mWebView.loadDataWithBaseURL("http://www.jcodecraeer.com", body, "text/html","utf-8",null);

If baseUrl is not specified as a http://www.jcodecraeer.com, this image will not be displayed.

The above example demonstrates the usage of loadDataWithBaseURL. We can directly load the html content in a string, and sometimes the content is read from the local webpage file under the assets Directory. Below we willThe content in html/test1.html is loaded using LoadData:

1234567891011121314151617 String data = "";try{    // To read files in the assets Directory, use the AssetManager object's Open method to Open the file.    InputStream is = getAssets().open("html/test2.html");    // The loadData () method requires a string, so we need to convert the file into a string.    ByteArrayBuffer baf = newByteArrayBuffer(500);    int count = 0;    while((count = is.read()) != -1) {        baf.append(count);    }    data = EncodingUtils.getString(baf.toByteArray(), "utf-8");}catch(IOException e) {    e.printStackTrace();}// Either of the following methods can be loaded successfullymWebView.loadData(data,"text/html","utf-8");// wv.loadDataWithBaseURL("", data, "text/html", "utf-8", "");

This method is used to read files.loadDataLoad andmWebView.loadUrl("file:///android_asset/html/test1.html") Is consistent,loadDataBecause no base url is specified,html/test1.htmlSome resource files or link addresses in the file will be invalid.

The difference between loadDataWithBaseURL and loadData is that HTML data in loadData () cannot contain '#', '% ','\','? 'Four special characters. During normal testing, your data contains these characters, but there is no problem. You can replace them when there is a problem.

%. A page error cannot be found. The page is garbled. See the symbol for garbled style.

#, It will invalidate your goBack, but canGoBAck can be used. Therefore, the return button takes effect, but cannot be returned.


WebView content processing


In android, The webView control padding does not work.
There is a WebView in a layout file. If you want to use the padding attribute to leave some blank spaces between the left and right sides, but the padding attribute cannot be left or right, the content will be displayed by pasting and moving the position of the scroll bar on the right. Android bug. Using a peripheral layout containing webview can be improved, but it cannot be completely solved. In fact, the correct method is to add padding to the css loaded by webView, and there is no need to change the xml layout file for padding.


Specify the url when overwriting shouldOverrideUrlLoading.

Specify to enable webview only when the url contains eoe.cn. Otherwise, start the browser.

123456789101112 @Overridepublic boolean shouldOverrideUrlLoading(WebView view, String url) {    LogUtil.i(this,"url="url);    if( url.contains("eoe.cn") == true){        view.loadUrl(url);        returntrue;    }else{        Intentin= newIntent (Intent.ACTION_VIEW , Uri.parse(url));        startActivity(in);        returntrue;    }}


Android: scrollbarStyle controls the scroll bar position

WebView has an attribute for setting the scroll bar position: android: scrollbarStyle can be insideOverlay or outsideOverlay. The difference between the two is that the style of SCROLLBARS_INSIDE_OVERLAY is that the scroll bar is in the entire page, similar to the padding in css, let's take a look at the figure below the code, which is very clear.

mWebView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);

MWebView. setScrollBarStyle (View. SCROLLBARS_INSIDE_OVERLAY );


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.