package com.dream.myapplication; import android.app.ProgressDialog;import android.content.Intent;import android.net.Uri;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.KeyEvent;import android.webkit.WebChromeClient;import android.webkit.WebSettings;import android.webkit.WebView;import android.webkit.WebViewClient;import android.widget.Toast; public class MainActivity extends AppCompatActivity { private String url = "https://www.baidu.com"; private WebView webView; private ProgressDialog dialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Uri uri = Uri.parse(url); // Intent intent = new Intent(Intent.ACTION_VIEW,uri); //startActivity(intent); init(); } private void init() { webView = (WebView) findViewById(R.id.web_view); webView.loadUrl(url); //webview中打开网页 webView.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { //返回值为true的时候,控制网页在webView中打开,false调用系统/第三方浏览器 view.loadUrl(url); return true; } }); 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) { //网页加载完毕,关闭 closeDialog(); } else { //网页加载中,打开Dialog openDialog(newProgress); } } }); } private void openDialog(int newProgress) { if(dialog==null){ dialog = new ProgressDialog(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){ //Toast.makeText(this,webView.getUrl(),Toast.LENGTH_SHORT).show(); if(webView.canGoBack()){ webView.goBack(); return true; }else { System.exit(0); } } return super.onKeyDown(keyCode, event); }}
时间: 2024-10-10 13:23:01