标签:android style blog http color os io java ar
1.res/layout/activity_main.xml加入代码,需要在xml布局文件中声明WebView组件
<WebView android:id="@+id/webview" android:layout_width="fill_parent" android:layout_height="fill_parent" />
2.在Activity中实例化WebView,并且可通过loadUrl(url)方法打开指定url资源
package com.example.webview; import android.app.Activity; import android.app.ProgressDialog; import android.os.Bundle; import android.view.KeyEvent; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; public class MainActivity extends Activity { private WebView webView; private String url = "http://www.baidu.com"; private ProgressDialog progressDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initWebView(); } private void initWebView() { webView = (WebView) findViewById(R.id.webview);// 获取控件 webView.loadUrl(url);// 载入指定url(系统自带浏览器,若想用自身webview需要重写方法,提供client) WebSettings webSettings = webView.getSettings();// 获取配置信息 webSettings.setJavaScriptEnabled(true);// 是否允许加载js文件 webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);// 打开缓存 webView.setWebViewClient(new WebViewClient() { /** * 重写shouldOverrideUrlLoading,返回值若为true则用webview,false则是系统自身浏览器 */ @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } }); webView.setWebChromeClient(new WebChromeClient() { @Override public void onProgressChanged(WebView view, int newProgress) {// newProgress当前进度 if (newProgress == 100) { // 加载完毕,关闭进度条 closeProgressDialog(); } else { //加载未完成,显示进度 showProgressDialog(newProgress); } super.onProgressChanged(view, newProgress); } private void closeProgressDialog() { progressDialog.dismiss(); progressDialog=null; } private void showProgressDialog(int newProgress) { if (progressDialog == null) { progressDialog = new ProgressDialog(MainActivity.this); progressDialog.setTitle("页面正在加载中..请稍后"); progressDialog .setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);//设置进度条样式 progressDialog.setProgress(newProgress);//设置进度 progressDialog.show(); } else { progressDialog.setProgress(newProgress); progressDialog.show(); } } }); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) {// keyCode代表按键的数字标示符 if (keyCode == KeyEvent.KEYCODE_BACK) { if (webView.canGoBack()) { webView.goBack(); return true; } else { System.exit(0); } } return super.onKeyDown(keyCode, event); } }
3.如果出现 webpage not available 在AndroidManifest.xml加入以下代码
<uses-permission android:name="android.permission.INTERNET"/>
详情查看 http://www.cnblogs.com/lichenwei/p/3959345.html
标签:android style blog http color os io java ar
原文地址:http://www.cnblogs.com/wesky/p/3962784.html