WebView与ProgressDialog结合

WebView组件支持直接加载网页,可以将其视为一个浏览器,要实现该功能,具体步骤如下:

webview.xml

<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
    <WebView android:id="@+id/webview"
    	android:layout_width="fill_parent"
    	android:layout_height="fill_parent"/>
</LinearLayout>

 

WebViewActivity.java

public class WebViewActivity extends Activity{
	private WebView webView;
	
	private AlertDialog alertDialog;
	private ProgressDialog progressBar;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.webview);
		//加载WebView
		initWebView();
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()){
			webView.goBack();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
	
	class MyWebViewClient extends WebViewClient{

		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			view.loadUrl(url);
			return true;
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			if(progressBar.isShowing()){
				progressBar.dismiss();
			}
		}

		@Override
		public void onReceivedError(WebView view, int errorCode,
				String description, String failingUrl) {
			Toast.makeText(WebViewActivity.this, "网页加载出错!", Toast.LENGTH_LONG);
			
			alertDialog.setTitle("ERROR");
			alertDialog.setMessage(description);
			alertDialog.setButton("OK", new DialogInterface.OnClickListener(){
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
				}
			});
			alertDialog.show();
		}
		
		
		
	}
	
	protected void initWebView(){
		//设计进度条
		progressBar = ProgressDialog.show(WebViewActivity.this, null, "正在进入网页,请稍后…");
		//获得WebView组件
		webView = (WebView) this.findViewById(R.id.webview);
		
		webView.getSettings().setJavaScriptEnabled(true);
		
		webView.loadUrl("http://www.baidu.com");
		
		alertDialog = new AlertDialog.Builder(this).create();
		
		//设置视图客户端
		webView.setWebViewClient(new MyWebViewClient());
	}
}

 最后,需要在**Manifest.xml中添加访问互联网的权限,否则不能显示:

<uses-permission android:name="android.permission.INTERNET"/>

 运行结果:

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值