public class MainActivity extends AppCompatActivity { private WebView webView; private String url = "http://2014.qq.com/"; private ProgressDialog dialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); } private void init() { webView = (WebView)findViewById(R.id.webview); //加载网页地址 webView.loadUrl(url); //重写shouldOverrideUrlLoading方法使网页可以在应用中显示 而不是系统浏览器 webView.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) {// return super.shouldOverrideUrlLoading(view, url); view.loadUrl(url); return true; } }); //启用支持JavaScript WebSettings settings = webView.getSettings(); settings.setJavaScriptEnabled(true); //WebView加载页面优先使用缓存 settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); webView.setWebChromeClient(new WebChromeClient() { @Override public void onProgressChanged(WebView view, int newProgress) { if (newProgress == 100) { //加载完毕 关闭ProgressDialog closeDialog(); } else { //正在加载 打开ProgressDialog openDialog(newProgress); } } }); } private void openDialog(int newProgress) { if(dialog == null){ dialog = new ProgressDialog(MainActivity.this); dialog.setTitle("正在拼命加载..."); //设置标题 dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); //设置样式 dialog.setProgress(newProgress); //更新内容 dialog.show(); //显示出来 } else{ dialog.setProgress(newProgress); } } private void closeDialog() { if(dialog != null && dialog.isShowing()){ dialog.dismiss(); //取消显示 dialog = null; } } //改写手机物理按键 返回逻辑 @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_BACK){ if(webView.canGoBack()) { webView.goBack(); //返回上一页面 return true; } else { System.exit(0); //推出程序n b } } return super.onKeyDown(keyCode, event); }