注意:要在清单文件中加入访问网络的权限------<uses-permission android:name="android.permission.INTERNET"/>
public class MainActivity extends Activity implements OnClickListener {
private EditText et_address;
private Button bt_search;
private WebView webview;
private ProgressDialog pd;
@Override
protected void onCreate(Bundle savedInstanceState) {
// 去掉标题栏
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_address = (EditText) findViewById(R.id.et_address);
bt_search = (Button) findViewById(R.id.bt_search);
webview = (WebView) findViewById(R.id.webview);
pd = new ProgressDialog(this);
pd.setMessage("加载中...");
et_address.setText("http://www.baidu.com");
bt_search.setOnClickListener(this);
// 获取webview的设置
WebSettings settings = webview.getSettings();
// 使webview支持缩放
settings.setSupportZoom(true);
settings.setBuiltInZoomControls(true);
// 如果访问的页面中有JavaScript,则webview必须支持JavaScript
settings.setJavaScriptEnabled(true);
// 取消webview滚动条
webview.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
// 设置webview从自己的浏览器打开网页
webview.setWebViewClient(new WebViewClient() {
@Override
/**
* 在这个方法中我们可以做很多操作,如果我们读取到某些特殊的URL,于是就不打开地址,
* 取消这个操作,进行预先定义的其他操作,这对一个程序是非常必要的。
*/
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
pd.show();
}
@Override
public void onPageFinished(WebView view, String url) {
pd.dismiss();
}
});
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bt_search:
String url = et_address.getText().toString();
// webview加载相应的网页
webview.loadUrl(url);
break;
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && webview.canGoBack()) {
webview.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.addSubMenu(0, 0, 0, "刷新");
menu.addSubMenu(0, 0, 1, "后退");
menu.addSubMenu(0, 0, 2, "前进");
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getOrder()) {
case 0:
// 重新加载(刷新)
webview.reload();
break;
case 1:
if (webview.canGoBack()) {
// 后退
webview.goBack();
} else {
Toast.makeText(MainActivity.this, "不能退了!", 0).show();
}
break;
case 2:
if (webview.canGoForward()) {
// 前进
webview.goForward();
} else {
Toast.makeText(MainActivity.this, "不能前进了!", 0).show();
}
break;
}
return super.onOptionsItemSelected(item);
}
}