在安卓開發過程中,很多時候我們需要用到WebView控件,下面以一個例子進行說明。
功能描述:進入界面後自動加載綁定的網址。
1、首先需要完成界面的開發,代碼如下所示(activity_history):
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".HistoryData" >
<WebView
android:id="@+id/webView2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" />
</RelativeLayout>
2、在第一步,我們已經完成了界面的開發,接下來打開對應的java文件,編寫如下代碼:
package com.sw.xmk;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
public class HistoryData extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history);
WebView webview = (WebView)findViewById(R.id.webView2);
//支持javascript
webview.getSettings().setJavaScriptEnabled(true);
//加載網頁
webview.loadUrl("http://10.0.2.2:8080/xmk/webpage/menu/allData.action");
// WebSettings websettings = webview.getSettings();
// //居中
// //websettings.setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
// //自適應
// websettings.setUseWideViewPort(true);
// websettings.setLoadWithOverviewMode(true);
//手指縮放
webview.getSettings().setSupportZoom(true);
webview.getSettings().setBuiltInZoomControls(true);
}
}
注意:別忘了還還要在AndroidManifest.xml中進行activity的聲明。
運行效果如下所示: