Android 19 (WebView usage)
Android provides a WebView control, which enables you to embed a browser in your application to easily display various web pages. Next, let's learn a simple usage. Create a WebViewTest project and modify the code in activity_main.xml as follows:
Then modify the code in MainActivity as follows:
Package com. jack. webviewtest; import android. OS. bundle; import android. app. activity; import android. view. menu; import android. webkit. webView; import android. webkit. webViewClient; public class MainActivity extends Activity {private WebView webView; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); // obtain the WebView instance webView = (We BView) findViewById (R. id. web_view); // call getSettings () to set some browser attributes and call the setJavaScriptEnabled method to enable WebView to support the javascript script webView. getSettings (). setJavaScriptEnabled (true);/** call the setWebViewClient () method, pass in the WebViewClient Anonymous class as the parameter, and then override the * shouldOverrideUrlLoading method, this indicates that when you need to jump from one web page to another, we want the target * web page to be displayed in the current WebView, instead of opening the system browser. **/WebView. setWebViewClient (new WebViewClient () {@ Overridepublic boolean shouldOverrideUrlLoading (WebView view, String url) {// TODO Auto-generated method stubview. loadUrl (url); // return true when loading a new webpage based on input parameters; // It indicates that the current WebView can process requests for opening a new webpage, you do not need to use the system browser}; // call the loadUrl () method and pass in the URL to display the corresponding web page content webView. loadUrl (http://www.baidu.com) ;}@ Overridepublic boolean onCreateOptionsMenu (Menu menu) {// Inflate the menu; this adds items to the action bar if it is present. getMenuInflater (). inflate (R. menu. main, menu); return true ;}}
In addition, you must note that because the program uses the network function and the permission must be declared to access the network, we have to modify the AndroidManifest. xml file and add the permission statement,
Before you start running, you must first ensure that your mobile phone or simulator is connected to the Internet. If you are using a simulator, you only need to ensure that your computer can access the Internet normally. Then you can run the program.
We can see that the WebViewTest program now has a simple browser function, not only successfully displaying the Baidu homepage, but also browsing more webpages by clicking the link.
At this point, the simple use of WebView is over.