package com.vip890.guy; import android.app.ProgressDialog; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.KeyEvent; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; /** * WebView */ public class MainActivity extends AppCompatActivity { private String url = "http://2016.qq.com"; private WebView mWebView; private ProgressDialog mProgressDialog; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mWebView = (WebView) findViewById(R.id.webView); mWebView.loadUrl(url);//加载web网页 加载本地资源文件 mWebView.setWebViewClient(new WebViewClient(){ @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } }); WebSettings settings = mWebView.getSettings(); settings.setJavaScriptEnabled(true); settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);//启用缓存 mWebView.setWebChromeClient(new WebChromeClient(){ @Override public void onProgressChanged(WebView view, int newProgress) { super.onProgressChanged(view, newProgress); if(newProgress == 100){ closeDialog(); } else { openDialog(newProgress); } } }); } private void closeDialog() { if(mProgressDialog != null && mProgressDialog.isShowing()){ mProgressDialog.dismiss(); mProgressDialog = null; } } private void openDialog(int newProgress) { if(mProgressDialog == null){ mProgressDialog=new ProgressDialog(MainActivity.this); mProgressDialog.setTitle("正在加载"); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); mProgressDialog.setProgress(newProgress); mProgressDialog.show(); }else{ mProgressDialog.setProgress(newProgress); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_BACK){ if(mWebView.canGoBack()){ mWebView.goBack(); return true; } else { System.exit(0); } } return super.onKeyDown(keyCode, event); } }
//权限声明 <uses-permission android:name="android.permission.INTERNET"/>
时间: 2024-09-29 23:06:38