Android network function is very powerful. The WebView component supports direct loading of web pages. It can be regarded as a browser. To implement this function, the specific steps are as follows
1. Declare WebView## in the layout file
#2. Instantiate WebView in Activity
3. Call the loadUrl() method of WebView to load the specified URL address web page
4. In order to allow WebView to respond to the hyperlink function , call the setWebViewClient() method to set the WebView client
5. In order to allow WebView to support the rollback function, override the onKeyDown() method
6. Be sure to note: in the AndroidManifest.xml file Add permission to access the Internet, otherwise it cannot be displayed
WebViewTest.java
/* * @author hualang */ package org.hualang.webview; import android.app.Activity; import android.os.Bundle; import android.view.KeyEvent; import android.webkit.WebView; import android.webkit.WebViewClient; public class WebViewTest extends Activity { /** Called when the activity is first created. */ private WebView webview; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); webview=(WebView)findViewById(R.id.webview); //设置WebView属性,能够执行JavaScript脚本 webview.getSettings().setJavaScriptEnabled(true); //加载URL内容 webview.loadUrl("http://www.baidu.com"); //设置web视图客户端 webview.setWebViewClient(new MyWebViewClient()); } //设置回退 public boolean onKeyDown(int keyCode,KeyEvent event) { if((keyCode==KeyEvent.KEYCODE_BACK)&&webview.canGoBack()) { webview.goBack(); return true; } return super.onKeyDown(keyCode,event); } //web视图客户端 public class MyWebViewClient extends WebViewClient { public boolean shouldOverviewUrlLoading(WebView view,String url) { view.loadUrl(url); return true; } } }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <WebView android:id="@+id/webview" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </LinearLayout>