public class WebViewTest extends Activity {
private WebView wv;
private EditText et;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
wv = (WebView) findViewById(R.id.webview_wv);
wv.loadUrl("http://www.baidu.com");
initWV();
et = (EditText) findViewById(R.id.webview_et);
et.setSelection(et.getText().length());
}
private void initWV() {
// TODO Auto-generated method stub
//設置內核,支持ajax
wv.setWebChromeClient(new WebChromeClient());
//new WebViewClient()默認基於webkit內核
wv.setWebViewClient(new WebViewClient(){
//從一個網頁跳到另一個網頁的方式,return true則爲目標頁面在當前webView打開,不會調用系統默認瀏覽器
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
return true;
}
//當頁面加載完畢調用的方法
@Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
Toast.makeText(WebViewTest.this, "加載完畢!", 0).show();
super.onPageFinished(view, url);
}
//頁面開始加載時調用的方法
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
et.setText(url);
super.onPageStarted(view, url, favicon);
}
});
//設置支持js腳本
wv.getSettings().setJavaScriptEnabled(true);
//設置支持手指放大
wv.getSettings().setSupportZoom(true);
wv.getSettings().setBuiltInZoomControls(true);
}
public void load(View view){
//加載URL
wv.loadUrl(et.getText().toString().trim());
}
public void reload(View view){
//重新載入,刷新頁面
wv.reload();
}
public void back(View view){
//後退
wv.goBack();
}
//設置(攔截)手機上的按鍵觸摸時間
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
wv.goBack();
break;
default:
break;
}
return super.onKeyDown(keyCode, event);
}
}
xml代碼:
<?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" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="後退"
android:onClick="back"/>
<EditText
android:id="@+id/webview_et"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="http://www."
android:singleLine="true"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="進入"
android:onClick="load"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="刷新"
android:onClick="reload"
/>
</LinearLayout>
<WebView
android:id="@+id/webview_wv"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>