android使用webview加载网页

来源:互联网 发布:淘宝店家推荐 编辑:程序博客网 时间:2024/05/20 16:12
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")@Overrideprotected 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 ());  } @Overridepublic 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> 

 源代码

6 4
原创粉丝点击