Android uses native component webview to load Web pages and data _android

Source: Internet
Author: User

An introduction to this class in the API is basically this is a view that can display a Web page, such as:

Webview.loadurl (http://www.baidu.com/);

Show Results:

You can also load some HTML strings, such as:

String str = " 
 

Show Results:

This component allows you to display the Web page in your activity or jump to the browser to display the page. The above example shows a jump to the mobile browser display Baidu interface. In the WebView method below, we use the WebView method to restrict the Web page from being displayed on the current activity.

Let's stepbystep to demonstrate the use of webview.

One, loading web pages

1.WebView used to display Web pages, use must always be aware that we need to add network permissions

<uses-permission android:name= "Android.permission.INTERNET"/>

2. Add WebView tags to the XML layout and instantiate them in the activity

<webview
android:id= "@+id/main_webview"
android:layout_width= "match_parent"
android:layout_ height= "Match_parent"/>
webview = (webview) Findviewbyid (R.id.main_webview);

3. Then we can load a Web page via the WebView Loadurl method.

Webview.loadurl (http://www.baidu.com/);

4. But this loading of the page will jump to the mobile browser, how to limit the Web page displayed in the current activity, you need to set its browser mode to False
Add the following code:

WebView = (webview) Findviewbyid (R.id.main_webview);
Set WebView client
webview.setwebviewclient (new Webviewclient () {
@Override public
Boolean Shouldoverrideurlloading (webview view, String URL) {
return false;//returned false
}
});
Webview.loadurl ("http://www.baidu.com/");

The effect displayed:

This simply loads a Web page.

WebView also provides an abstract class websettings to set some of the basic content of the Web page that it displays, instantiated by using the WebView object's Get method to obtain

WebSettings websettings = Webview.getsettings ();

This class allows you to set a list of properties for WebView display Web pages

In order to see whether the property is effective I purposely will webview display of the Web page replaced, replaced by our company's Web site, first of all, to look at the page does not set a series of properties to display the style, you can see that the interface is obviously not and mobile screen adaptation, very poor user experience

Then I set up a series of properties that show the page through the WebSettings class

WebSettings websettings = Webview.getsettings ();
Allow WebView to execute JavaScript
websettings.setjavascriptenabled (true);
Allow JavaScript to automatically open Windows
websettings.setjavascriptcanopenwindowsautomatically (true);
Set Cache
websettings.setappcacheenabled (true);
Set caching mode, a total of four modes
Websettings.setcachemode (websettings.load_cache_else_network);
Set cache path
//Websettings.setappcachepath ("");
Supports scaling (Fit to current screen)
Websettings.setsupportzoom (true);
Adjusts the picture to the appropriate size
Websettings.setusewideviewport (true);
There are four ways to support content
Narrow_columns//The default is the
websettings.setlayoutalgorithm ( WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
Sets the screen control
Websettings.setdisplayzoomcontrols (true) that can be displayed;
Set default font Size
websettings.setdefaultfontsize (12);

After the setup is complete, look at the effects of the operation:

All code:

Manifest file: The most important thing is not to forget to add network permissions

<?xml version= "1.0" encoding= "Utf-8"?> <manifest xmlns:android=
"http://schemas.android.com/apk/res/" Android "
package=" Com.wu.webviewdemo ">
<uses-permission android:name=" Android.permission.INTERNET "/>
<application
android:allowbackup=" true "
android:icon=" @mipmap/ic_launcher "
android: Label= "@string/app_name"
android:supportsrtl= "true"
android:theme= "@style/apptheme" >
< Activity android:name= ". Mainactivity ">
<intent-filter>
<action android:name=" Android.intent.action.MAIN "/>
<category android:name= "Android.intent.category.LAUNCHER"/>
</intent-filter>
</ activity>
</application>
</manifest>

Layout file

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android=
"http://schemas.android.com/apk/" Res/android "
android:layout_width=" match_parent "
android:layout_height=" match_parent "
android:o" rientation= "vertical" >
<textview
android:layout_width= "Match_parent"
Wrap_content "
android:background=" #000 "
android:gravity=" center "
android:paddingbottom=" 10DP "
android:paddingtop= "10DP"
android:text= "use WebView"
android:textallcaps= "false"
Android: Textcolor= "#fff"/>
<webview
android:id= @+id/main_webview "android:layout_width=" Match_
Parent "
android:layout_height=" match_parent "/>
</LinearLayout>

Activity

Package Com.wu.webviewdemo;
Import android.support.v7.app.AppCompatActivity;
Import Android.os.Bundle;
Import android.webkit.WebSettings;
Import Android.webkit.WebView;
Import android.webkit.WebViewClient; public class Mainactivity extends Appcompatactivity {private WebView webview; @Override protected void onCreate (Bundle sa Vedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); WebView = (WebView)
Findviewbyid (R.id.main_webview); Set WebView client webview.setwebviewclient (new Webviewclient () {@Override public boolean shouldoverrideurlloading (
WebView view, String URL) {return false;//returned false}});
WebSettings websettings = Webview.getsettings ();
Allow WebView to execute JavaScript websettings.setjavascriptenabled (true);
Allow JavaScript to automatically open Windows websettings.setjavascriptcanopenwindowsautomatically (TRUE);
Set Cache websettings.setappcacheenabled (TRUE);
Set caching mode, a total of four modes websettings.setcachemode (websettings.load_cache_else_network); Set cache path//WebsettiNgs.setappcachepath ("");
Supports scaling (Fit to current screen) Websettings.setsupportzoom (true);
Adjusts the picture to the appropriate size websettings.setusewideviewport (true); Support content redistribution, there are four ways//The default is Narrow_columns Websettings.setlayoutalgorithm (WebSettings.LayoutAlgorithm.SINGLE_COLUMN
);
Sets the screen control Websettings.setdisplayzoomcontrols (true) that can be displayed;
Set default font Size websettings.setdefaultfontsize (12);
Webview.loadurl ("http://www.lanou3g.com/"); }
}

Second, loading HTML strings

In some Android development there is a situation where the display details page is not some simple text, not a simple Web page, but through the interface to provide us with HTML-written data, we often encounter this data by WebView loading, That's another way to use WebView.

public void LoadData (string data, String mimetype, String encoding)

1. First look at what the HTML string is like, in order to strengthen the persuasive and fitting reality, there is no own manufacturing strings (such as the opening example) but a piece of netease news content (old Guo and his apprentice news, I still like to listen to Guo Teacher's crosstalk, after all drinking Shantou)

Private String BODY = "<p> <b> NetEase Entertainment news September 7 </b> (Wen/Xiao Yi)" +
"early this morning, Guo Crane character generation apprentice in micro-bo German Cloud Society table loyalty, said himself before the outside privately rejoined , leaving German Cloud society, "+
" because of shame two years without master Guo and Mrs. Song contact, this should be cleared the door, but thanks to master Guo never abandon. "+
" then, Guo forwarded the micro-blog and attached to the article "error can improve the great." Plus a few days ago Cao Yunqin and He Yunwei tore Guo Insider, "+
" This should be the end of the various disputes between Guo and disciple if this goes on, it is difficult to complete. </p><p> <b> Han Hexiao Micro bo Original: "+
" </b></p><p> 2006 test into the crane Word division named Crane Xiao, June 13, 2009 Mr. Guo received me as a disciple of Guo. "+
" over the years to eat, live, The Apprentice in who remains undistracted base, Master Mrs. Song a penny not taken. In 2010, Master Mrs. Song gave me and my wife a red envelope and a wedding ring, "+
" and offered us a wedding house at who remains undistracted base. In September 2014, I went to the field privately for personal reasons. Later returned to Beijing ashamed to face mentor, "+
" two years did not dare to meet with the teacher. After the development of Shanghai in June 2016, during the master's performance in Shanghai, she finally summoned the courage to admit to master, "+
" master generosity forgave me. After two months back to Beijing, a special trip to the home to see Mrs. Song, and Seek forgiveness. To 鶴 Xiao's mistakes, "+
" can lead to "clear the door", the restoration of who remains undistracted family tree, the teacher does not abandon, give "temporarily stay to see" is the acts of children spared. "+
" the Guilty disciple 鶴 Xiao Gratitude teacher to teach the grace, not abandon the feeling. 鶴 Xiao Although thousands of away from the capital, will be forever heart who remains undistracted. "+
" has not dared to forget the teachings of the mentor, steadfast do art, good man! Only wish Master Mrs. Song body Aetna! Acts son 鶴 Xiao Dushou affairs yao! </p> ";

2. Set the default character encoding, commonly used in Android UTF-8

WebSettings websettings = Webview.getsettings ();
Websettings.setdefaulttextencodingname ("UTF-8");

3. Then call the WebView LoadData method

Webview.loaddata (Body, "text/html; Charset=utf-8 ", NULL);

The display effect is as follows:

The following are all the code, the layout continues to use (first, load the page), the Code section is not much changed, as follows:

Package Com.wu.webviewdemo;
Import android.support.v7.app.AppCompatActivity;
Import Android.os.Bundle;
Import android.webkit.WebSettings;
Import Android.webkit.WebView;
Import android.webkit.WebViewClient; public class Mainactivity extends Appcompatactivity {private WebView webview; private String BODY = "<p> <b> NetEase Entertainment News September 7 </b> (Wen/Xiao Yi) "+" Early today, Guo Crane character generation apprentice in micro-blog issued to German Cloud society table loyalty, said himself before outside privately rejoined, leave German Cloud society, "+" because of shame two years without master Guo and Mrs. Song contact, this should be clear the door, But thanks to master Guo, he never leaves. "+" Then, Guo forwarded the micro-blog and attached to the article "error can improve the great." Plus a few days ago Cao Yunqin and He Yunwei tore Guo Insider, "+" This should be the end of the various disputes between Guo and disciple if this goes on, it is difficult to complete. </p><p> <b> Han Hexiao Micro bo Original: "+" </b></p><p> 2006 test into the crane Word division named Crane Xiao, June 13, 2009 mentor Mr. Guo received me as Guo Disciple. "+" over the years to eat, live, The Apprentice in who remains undistracted base, Master Mrs. Song a penny not taken. In 2010, Master Mrs. Song gave me and my wife a red envelope and a wedding ring, "+" and offered us a wedding house at who remains undistracted base. In September 2014, I went to the field privately for personal reasons. Later returned to Beijing ashamed to face mentor, "+" two years did not dare to meet with the teacher. After the development of Shanghai in June 2016, during the master's performance in Shanghai, she finally summoned the courage to admit to master, "+" Master generosity forgave me. After two months back to Beijing, a special trip to the home to see Mrs. Song, and Seek forgiveness. To 鶴 Xiao's mistakes, "+" can lead to "clear the door", the restoration of who remains undistracted family tree, the teacher does not abandon, give "temporarily stay to see" is the acts of children spared. "+" the Guilty disciple 鶴 Xiao Gratitude teacher to teach the grace, not abandon the feeling. 鶴 Xiao Although thousands of away from the capital, will be forever heart who remains undistracted. "+" has not dared to forget the teachings of the mentor, steadfast do art, good man! Only wish Master Mrs. Song body Aetna! Acts son 鶴 Xiao Dushou affairs remote Worship!
</p> "; @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (
R.layout.activity_main);
WebView = (webview) Findviewbyid (R.id.main_webview);
WebSettings websettings = Webview.getsettings ();
Websettings.setdefaulttextencodingname ("UTF-8"); Webview.loaddata (Body, "text/html;
Charset=utf-8 ", NULL); }
}

The above is a small addendum to the introduction of Android using native component WebView to load Web pages and data, hope to be helpful to everyone, if you have any questions welcome to my message, small series will promptly reply to everyone, here also thank you for the cloud Habitat Community website support!

Related Article

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.