沒事兒來一更
android使用webview加載網頁
package com.example.webview; import android.os.Bundle; import android.annotation.SuppressLint; import android.app.Activity; import android.view.KeyEvent; import android.view.Menu; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; public class MainActivity extends Activity { private WebView webview; @SuppressLint( "SetJavaScriptEnabled" ) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); webview = (WebView) findViewById(R.id.webview); WebSettings webSettings = webview.getSettings(); //設置WebView屬性,能夠執行Javascript腳本 webSettings.setJavaScriptEnabled( true ); //設置可以訪問文件 webSettings.setAllowFileAccess( true ); //設置支持縮放 webSettings.setBuiltInZoomControls( true ); //加載需要顯示的網頁 webview.loadUrl( "http://www.baidu.com" ); //設置Web視圖 webview.setWebViewClient( new webViewClient ()); } @Override public 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 ; } @Override //設置回退 //覆蓋Activity類的onKeyDown(int keyCoder,KeyEvent event)方法 public boolean onKeyDown( int keyCode, KeyEvent event) { if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) { webview.goBack(); //goBack()表示返回WebView的上一頁面 return true ; } finish(); //結束退出程序 return false ; } //Web視圖 private class webViewClient extends WebViewClient { public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true ; } } } |
xml代碼
<?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>