English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
在Api中关于这个类的介绍大致就是这是一个可以显示网页的视图,如:
webView.loadUrl(http://www.baidu.com/);
Display result:
还可以加载一些html的字符串,如:
String str = "<html><body>You scored <b>192</b> points.</body></html>"; webView.loadData(str, "text/html", null);
Display result:
This component can display web pages in your Activity or jump to the browser to display web pages. The example above shows jumping to the mobile browser to display the Baidu interface. In the introduction of WebView methods below, we will use the methods of WebView to limit the display of web pages on the current Activity.
Let's demonstrate the use of WebView step by step below.
1. Load web page
1.WebView is used to display web pages, and it is necessary to add network permissions at all times when using it
<uses-permission android:name="android.permission.INTERNET"/>
2.Add the WebView tag in the XML layout and instantiate it 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.After that, we can load a web page through the loadUrl method of WebView
webView.loadUrl(http://www.baidu.com/);
4.However, the web page loaded in this way will jump to the mobile browser. To limit the display of the web page 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 the WebView client webView.setWebViewClient(new WebViewClient(){ @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { return false;// 返回false } }); webView.loadUrl("http://www.baidu.com/");
Display effect:
This simply loads a web page.
WebView also provides an abstract class WebSettings to set some basic content of the web pages it displays, and the instantiation is obtained through the get method of the WebView object
WebSettings webSettings = webView.getSettings();
This class can be used to set a series of properties for displaying web pages in WebView
To check if the properties take effect, I specially changed the web page displayed by WebView, replacing it with our company's website. Let's first take a look at the style of the web page displayed without setting a series of properties. It can be seen that the interface is obviously not compatible with the mobile phone screen, and the user experience is very poor
Later, I set a series of properties for displaying web pages through the WebSettings class
WebSettings webSettings = webView.getSettings(); // return false }); // Enable WebView to execute JavaScript Allow JavaScript to automatically open windows // webSettings.setJavaScriptCanOpenWindowsAutomatically(true); Set the cache // webSettings.setAppCacheEnabled(true); Set the cache mode, there are a total of four modes // Set the cache path // webSettings.setAppCachePath(""); // Support zoom (fit to the current screen) webSettings.setSupportZoom(true); // Adjust the size of the image to a suitable size webSettings.setUseWideViewPort(true); // Supports content re-layout, there are a total of four methods // The default is NARROW_COLUMNS webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN); // Set the screen controls that can be displayed webSettings.setDisplayZoomControls(true); // Set the default font size webSettings.setDefaultFontSize(12);
After setting up, let's take a look at the running effect:
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:orientation="vertical"> <TextView android:layout_width="match_parent" android:layout_height="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 savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); webView = (WebView) findViewById(R.id.main_webview); // Set the WebView client webView.setWebViewClient(new WebViewClient(){ @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { return false;// 返回false } }); WebSettings webSettings = webView.getSettings(); // return false }); // Enable WebView to execute JavaScript Allow JavaScript to automatically open windows // webSettings.setJavaScriptCanOpenWindowsAutomatically(true); Set the cache // webSettings.setAppCacheEnabled(true); Set the cache mode, there are a total of four modes // Set the cache path // webSettings.setAppCachePath(""); // Support zoom (fit to the current screen) webSettings.setSupportZoom(true); // Adjust the size of the image to a suitable size webSettings.setUseWideViewPort(true); // Supports content re-layout, there are a total of four methods // The default is NARROW_COLUMNS webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN); // Set the screen controls that can be displayed webSettings.setDisplayZoomControls(true); // Set the default font size webSettings.setDefaultFontSize(12); webView.loadUrl("http://www.lanou3g.com/"); } }
Second, loading HTML string
In some Android development, you may encounter a situation where the detail page is not just simple text or a simple web page, but data written in HTML provided through an interface. When encountering such data, the usual approach we take is to load it using WebView, which makes use of another method of WebView
public void loadData(String data, String mimeType, String encoding)
1First, let's take a look at what the HTML string looks like. To enhance persuasiveness and practicality, I did not create a string myself (as in the opening example) but scraped some content from a NetEase news article (news about Lao Guo and his apprentice, by the way, I still enjoy listening to Master Guo's crosstalk, after all, drinking and getting a haircut are a pair of good friends)
private String body = "<p> <b>NetEase Entertainment exclusive article"9month7reporting</b>(Wen/Xiaoyi) + "This morning, Guo Degang's He Zi generation disciple wrote a microblog expressing loyalty to Di Yun Society, saying that he had secretly taken on work outside before leaving Di Yun Society," + "Due to shame, I haven't contacted Master Guo Degang and the master's wife for two years, and I should have been expelled from the school, but I was grateful that Master Guo Degang did not abandon me. + "Subsequently, Guo Degang forwarded the microblog and wrote, "To correct one's mistakes is the best thing to do." Added to the recent scandal involving Cao Yujin and He Yunwei's fight with Guo Degang," + "The various disputes between Guo Degang and his disciples should have ended, but if it continues like this, it may be difficult to end completely./p><p> <b>Han Xiaoxiao's original Weibo:" + "</b></p><p> 2006year, I was admitted to the He Zi class and named He Xiaoxiao.2009year6month13day, Master Guo Degang took me as his Guo school disciple. + "For several years, I lived, studied, and practiced in the Di Yun base, and the master and the master's wife did not take a single cent.2010year, the master and the master's wife gave me and my lover red envelopes and wedding rings," + "and provided us with a wedding room at the Di Yun base.2014year9month, due to personal reasons, I secretly went to develop in other places. Later, I returned to the capital and was ashamed to face my teacher," + "For two years, I dared not meet my teacher. Later, I developed in Shanghai,"2016year6During the master's Shanghai performance, I finally gathered the courage to confess my mistake to the master," + "The master showed great leniency and forgave me. Two months after returning to the capital, I specially visited the master's house to see the master's wife and sought her forgiveness. Regarding the mistakes made by He Xiaoxiao," + "It is enough to lead to a 'Qingmen', when revising the genealogy of De Yun family, I was grateful for the teacher's not giving up, and giving me the 'temporary observation' is actually opening a way for the disciple." + "The sinner鹤晓 is grateful for the teacher's teaching and the undying affection. Although鹤晓 is thousands of miles away from the capital, I will always be loyal to De Yun." + "I dare not forget my teacher's sincere teaching, to be steady in art and to be a good person! May my teacher and mother-in-law be healthy! Disciple鹤晓 bows deeply from afar!"/p>";
2.Set the default character encoding, UTF-8 is commonly used in Android.-8
WebSettings webSettings = webView.getSettings(); webSettings.setDefaultTextEncodingName("UTF-8");
3.After that, call the WebView's loadData method
webView.loadData(body, "text/html; charset=UTF-8", null);
The display effect is as follows:
The following is all the code, the layout continues to use (1, Load Web Page), and the code part has not changed much, 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 exclusive article"9month7reporting</b>(Wen/Xiaoyi) + "This morning, Guo Degang's He Zi generation disciple wrote a microblog expressing loyalty to Di Yun Society, saying that he had secretly taken on work outside before leaving Di Yun Society," + "Due to shame, I haven't contacted Master Guo Degang and the master's wife for two years, and I should have been expelled from the school, but I was grateful that Master Guo Degang did not abandon me. + "Subsequently, Guo Degang forwarded the microblog and wrote, "To correct one's mistakes is the best thing to do." Added to the recent scandal involving Cao Yujin and He Yunwei's fight with Guo Degang," + "The various disputes between Guo Degang and his disciples should have ended, but if it continues like this, it may be difficult to end completely./p><p> <b>Han Xiaoxiao's original Weibo:" + "</b></p><p> 2006year, I was admitted to the He Zi class and named He Xiaoxiao.2009year6month13day, Master Guo Degang took me as his Guo school disciple. + "For several years, I lived, studied, and practiced in the Di Yun base, and the master and the master's wife did not take a single cent.2010year, the master and the master's wife gave me and my lover red envelopes and wedding rings," + "and provided us with a wedding room at the Di Yun base.2014year9month, due to personal reasons, I secretly went to develop in other places. Later, I returned to the capital and was ashamed to face my teacher," + "For two years, I dared not meet my teacher. Later, I developed in Shanghai,"2016year6During the master's Shanghai performance, I finally gathered the courage to confess my mistake to the master," + "The master showed great leniency and forgave me. Two months after returning to the capital, I specially visited the master's house to see the master's wife and sought her forgiveness. Regarding the mistakes made by He Xiaoxiao," + "It is enough to lead to a 'Qingmen', when revising the genealogy of De Yun family, I was grateful for the teacher's not giving up, and giving me the 'temporary observation' is actually opening a way for the disciple." + "The sinner鹤晓 is grateful for the teacher's teaching and the undying affection. Although鹤晓 is thousands of miles away from the capital, I will always be loyal to De Yun." + "I dare not forget my teacher's sincere teaching, to be steady in art and to be a good person! May my teacher and mother-in-law be healthy! Disciple鹤晓 bows deeply from afar!"/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 the method introduced by the editor to everyone on how to use the native component WebView to load web pages and data in Android, hoping it will be helpful to everyone. If you have any questions, please leave me a message, and the editor will reply to everyone in time. Thank you very much for everyone's support for the Yell Tutorial website!
Declaration: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been edited by humans, and does not assume relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email for reporting, and provide relevant evidence. Once verified, this site will immediately delete the content suspected of infringement.)