webView安卓简易浏览器制作

private WebView webView;
webView = (WebView) findViewById(R.id.webView);

webView.loadUrl("https://hao.balala.cn");

设置不跳转第三方浏览器

	webView.setWebViewClient(new WebViewClient() {
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			view.loadUrl(url);
			return super.shouldOverrideUrlLoading(view, url);
		}
	});

设置加载进度对话框

	prodialog = new ProgressDialog(this);
	// 启用JavaScript才能支持监听网页进度变化
	WebSettings setting = webView.getSettings();
	setting.setJavaScriptEnabled(true);
	webView.setWebChromeClient(new WebChromeClient() {
	
		public void onProgressChanged(WebView view, int newProgress) {
			// TODO Auto-generated method stub
			if (newProgress != 100) {
				prodialog.setTitle("数据加载中" + newProgress + "%");
				prodialog.setProgressStyle(prodialog.STYLE_HORIZONTAL);
				prodialog.setProgress(newProgress);
				prodialog.show();
			} else {
				prodialog.dismiss();
			}
			super.onProgressChanged(view, newProgress);
		}
	});

物理按键功能设置

@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == event.KEYCODE_BACK) {
			if (webView.canGoBack()) {
				webView.goBack();
			} else {
				Toast.makeText(this, "您的操作有误", 1).show();
			}
		}
		return super.onKeyDown(keyCode, event);
	}

**

完整代码演示

**

public class MainActivity extends Activity {
	private WebView webView;
	private ProgressDialog prodialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);


		webView = (WebView) findViewById(R.id.webView);

		webView.loadUrl("https://hao.balala.cn");
		// 设置不跳转第三方浏览器
		webView.setWebViewClient(new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				view.loadUrl(url);
			return super.shouldOverrideUrlLoading(view, url);
		}
	});

	// 设置加载进度对话框
	prodialog = new ProgressDialog(this);
	
	// 启用JavaScript才能支持监听网页进度变化
	WebSettings setting = webView.getSettings();
	setting.setJavaScriptEnabled(true);
	
	webView.setWebChromeClient(new WebChromeClient() {
		@Override
		public void onProgressChanged(WebView view, int newProgress) {
			// TODO Auto-generated method stub
			if (newProgress != 100) {
				prodialog.setTitle("数据加载中" + newProgress + "%");
				prodialog.setProgressStyle(prodialog.STYLE_HORIZONTAL);
				prodialog.setProgress(newProgress);
				prodialog.show();
			} else {
				prodialog.dismiss();
			}
			super.onProgressChanged(view, newProgress);
		}
	});
}

//物理按键功能设置
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == event.KEYCODE_BACK) {
			if (webView.canGoBack()) {
				webView.goBack();
			} else {
				Toast.makeText(this, "您的操作有误", 1).show();
			}
		}
		return super.onKeyDown(keyCode, event);
    	}
    }

webView安卓简易浏览器制作_第1张图片

你可能感兴趣的:(安卓学习)