Basic usage of webView in Android (1), androidwebview

Source: Internet
Author: User

Basic usage of webView in Android (1), androidwebview
WebViewIs a subclass of View that allows you to display webpages in the activity.

You can write a WebView to the layout file. For example, the following shows a WebView that fills up the entire screen:

1 <?xml version="1.0" encoding="utf-8"?>2 <WebView  xmlns:android="http://schemas.android.com/apk/res/android"3     android:id="@+id/webview"4     android:layout_width="fill_parent"5     android:layout_height="fill_parent"6 />

Load a webpage and useloadUrl():

WebView myWebView = (WebView) findViewById(R.id.webview);myWebView.loadUrl(http://www.example.com);  

Note: add the network access permission to manifest:

 

<manifest ... >     <uses-permission android:name="android.permission.INTERNET" />     ... </manifest>
Set the web page to be displayed for WebView

There are many ways to set WevView to display web pages:

Direct use of Internet pages:

myWebView.loadUrl(“http://www.google.com“);

For local files:

myWebView.loadUrl(“file:///android_asset/XX.html“); 

Local files are stored in the assets file.

You can also directly load html strings.Such:

String htmlString = "Use JavaScript in WebView

If the page you want to load uses JavaScript, youRequiredEnable JavaScript for your WebView.

Once enabled, you can also create an interface to interact between your application and JavaScript code.

Enabling JavaScriptYou can usegetSettings()Obtain WebSettings, and then usesetJavaScriptEnabled()Enable JavaScript:

WebView myWebView = (WebView) findViewById(R.id.webview);WebSettings webSettings = myWebView.getSettings();webSettings.setJavaScriptEnabled(true);

WebSettings provides many useful settings.

Process page browsing

When a user clicks a link in your WebView, the default behavior is that Android starts an app that processes URLs. Generally, the default browser opens and downloads the target URL.

However, you can overwrite this line in your WebView so that the connection is still opened in your WebView.

Then, based on the Web browsing history maintained in WebView, you can allow users to browse their web pages forward or backward.

Open all links in WebView

To open the user-clicked link, you only need to use the setWebViewClient () method to provideWebViewClientFor example:

WebView myWebView = (WebView) findViewById(R.id.webview);myWebView.setWebViewClient(new WebViewClient());

Now, you can open the link in your WebView.

More control on opening link locations

If you need more control over where to open the link, you can create your own class and inheritWebViewClientAnd then overwriteshouldOverrideUrlLoading()Method.

For example:

 1 private class MyWebViewClient extends WebViewClient 2     { 3         @Override 4         public boolean shouldOverrideUrlLoading(WebView view, String url) 5         { 6  7        if(Uri.parse(url).getHost().equals(www.example.com)) 8             { 9                 // This is my web site, so do not override; let my WebView load10                 // the page11                 return false;12             }13             // Otherwise, the link is not for a page on my site, so launch14             // another Activity that handles URLs15             Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));16             startActivity(intent);17             return true;18         }19     }

Open a specific link with your own WebView, and use a browser for other links (intent starts the default URL-based Activity ).

After the definition, pass the object of this class into the setWebViewClient () method.

WebView myWebView = (WebView) findViewById(R.id.webview);myWebView.setWebViewClient(new MyWebViewClient());

Practice Verification:When setWebViewClient (new WebViewClient () is set directly, the verification is correct, that is, all links are opened in WebView.

When the WebViewClient subclass object is set as a custom object, it is found that the link is still open from the default browser.

Browsing Web history rollback

When your WebView overwrites the URL loading behavior, it automatically accumulates a history for the accessed webpage. You can usegoBack()AndgoForward()The method moves forward or backward in this history.

For example, you can use the backend key to move the webpage back:

1/** 2 * click the button to respond. When you view a webpage in WebView, press the return key to return the webpage based on browsing history, if you do not perform this operation, the whole WebView returns to exit 3 */4 @ Override 5 public boolean onKeyDown (int keyCode, KeyEvent event) 6 {7 // Check if the key event was the Back button and if there's history 8 if (keyCode = KeyEvent. KEYCODE_BACK) & myWebView. canGoBack () 9 {10 // return key to return 11 myWebView. goBack (); 12 return true; 13} 14 // If it wasn't the Back key or there's no web page history, bubble up15 // to the default16 // system behavior (probably exit the activity) 17 return super. onKeyDown (keyCode, event); 18}

 CanGoBack ()Method returns true when the webpage can be retired.

Similarly, the canGoForward () method can check whether there are historical records that can be moved forward.

If you do not perform this check, onceGoBack ()AndgoForward()Methods reach the top of the history, and they will do nothing.

If this setting is not added, the WebView is returned as a whole when the user presses the Back key.

Program instance

Complete procedures are attached:

1 WebView Basic 2 3 import android. annotation. suppressLint; 4 import android. app. activity; 5 import android. content. intent; 6 import android.net. uri; 7 import android. OS. bundle; 8 import android. view. keyEvent; 9 import android. view. menu; 10 import android. webkit. webSettings; 11 import android. webkit. webView; 12 import android. webkit. webViewClient; 13 14 @ SuppressLint ("SetJavaScriptEnabled") 15 public class WebActivity extends Activity 16 {17 private WebView myWebView = null; 18 19 @ Override 20 public void onCreate (Bundle savedInstanceState) 21 {22 super. onCreate (savedInstanceState); 23 setContentView (R. layout. activity_web); 24 25 // open the webpage 26 myWebView = (WebView) findViewById (R. id. webview); 27 // 28 29 // myWebView. loadUrl ("http://www.cnblogs.com/mengdd/"); // blog link 30 myWebView. loadUrl ("http://www.baidu.com/"); // Baidu link 31 32 // JavaScript enabling (if the page to be loaded has JS Code, you must enable JS) 33 WebSettings webSettings = myWebView. getSettings (); 34 webSettings. setJavaScriptEnabled (true); 35 36 // open a link in WebView (the default action is to use a browser. WebView is used after setting this option) 37 // myWebView. setWebViewClient (new WebViewClient (); 38 // after this setting, all links will open 39 40 // stronger open Link Control in the current WebView: overwrite a WebViewClient class: in addition to the specified link to open from WebView, other links will open 41 myWebView by default. setWebViewClient (new MyWebViewClient (); 42 43} 44 45 @ Override 46 public boolean onCreateOptionsMenu (Menu menu) 47 {48 getMenuInflater (). inflate (R. menu. activity_web, menu); 49 return true; 50} 51 52/** 53 * Custom WebViewClient class, which opens special links from WebView, other links are still opened in the default browser 54*55 * @ author 1 56*57 */58 private class MyWebViewClient extends WebViewClient 59 {60 @ Override 61 public boolean shouldOverrideUrlLoading (WebView view, string url) 62 {63 if (Uri. parse (url) 64. getHost () 65. equals ("http://www.cnblogs.com/mengdd/archive/2013/02/27/2935811.html") 66 | Uri. parse (url ). getHost () 67. equals ("http://music.baidu.com/") 68 {69 // This is my web site, so do not override; let my WebView load 70 // the page 71 72 // This is an example on the official website. However, when I click a specific link, I still open it with a browser instead of my own WebView, add the following view. loadUrl (url) is still in the browser, no solution, do not know what is wrong 73 // view. loadUrl (url); 74 return false; 75} 76 // Otherwise, the link is not for a page on my site, so launch 77 // another Activity that handles URLs 78 Intent intent = new Intent (Intent. ACTION_VIEW, Uri. parse (url); 79 startActivity (intent); 80 return true; 81} 82} 83 84/** 85 * key response. When you view the webpage in WebView, when you press the return key, return by browsing history. Otherwise, the whole WebView returns 86 */87 @ Override 88 public boolean onKeyDown (int keyCode, KeyEvent event) 89 {90 // Check if the key event was the Back button and if there's history 91 if (keyCode = KeyEvent. KEYCODE_BACK) & myWebView. canGoBack () 92 {93 // return the return key to 94 myWebView. goBack (); 95 return true; 96} 97 // If it wasn't the Back key or there's no web page history, bubble up 98 // to the default 99 // system behavior (probably exit the activity) 100 return super. onKeyDown (keyCode, event); 101} 102 103}
References

A learning website recommended for Web:

Http://www.w3school.com.cn/

API Guides: Building Web Apps in WebView

Http://developer.android.com/guide/webapps/webview.html

Other Learning links:

Http://www.cnblogs.com/aimeng/archive/2012/05/24/2516547.html

Http://www.apkbus.com/android-44567-1-1.html

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.