让ProgressDialog在setCancelable(false)时按返回键可dismiss

最近发现Android4.0系统中ProgressDialog设置为setCancelable(true)时,点击ProgressDialog以外的区域也可以让ProgressDialog dismiss掉。但有时我们不希望是这样的效果,于是将ProgressDialog设置setCancelable(false),再点击ProgressDialog以外的区域就不会出现前面所说的情况了,然而这样以来再按返回键时就不起作用了,只能等待程序执行到dissmiss处为止。其实,只要为ProgressDialog添加KeyListener来对返回键予以处理就可以解决这个问题了。

  1. package cn.winfirm.examples.base;

  2. import android.app.Activity;
  3. import android.app.ProgressDialog;
  4. import android.content.DialogInterface;
  5. import android.content.DialogInterface.OnKeyListener;
  6. import android.os.Bundle;
  7. import android.view.KeyEvent;
  8. import android.view.Window;

  9. /**
  10.  * Activity的基类,带一个ProgressDialog,可双击取消其显示
  11.  *
  12.  * @author savant
  13.  *
  14.  */
  15. public class BaseActivity extends Activity {

  16.     private ProgressDialog progressDialog = null;

  17.     @Override
  18.     protected void onCreate(Bundle savedInstanceState) {
  19.         super.onCreate(savedInstanceState);
  20.         requestWindowFeature(Window.FEATURE_NO_TITLE);
  21.     }

  22.     /**
  23.      * show loading progress dialog
  24.      */
  25.     public void showDialog() {
  26.         if (null == progressDialog) {
  27.             progressDialog = ProgressDialog.show(BaseActivity.this, "", "正在加载,请稍候...");
  28.             progressDialog.setCancelable(false);
  29.         } else {
  30.             progressDialog.show();
  31.         }
  32.         progressDialog.setOnKeyListener(onKeyListener);
  33.     }

  34.     /**
  35.      * add a keylistener for progress dialog
  36.      */
  37.     private OnKeyListener onKeyListener = new OnKeyListener() {
  38.         @Override
  39.         public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
  40.             if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
  41.                 dismissDialog();
  42.             }
  43.             return false;
  44.         }
  45.     };

  46.     /**
  47.      * dismiss dialog
  48.      */
  49.     public void dismissDialog() {
  50.         if (isFinishing()) {
  51.             return;
  52.         }
  53.         if (null != progressDialog && progressDialog.isShowing()) {
  54.             progressDialog.dismiss();
  55.         }
  56.     }

  57.     /**
  58.      * cancel progress dialog if nesseary
  59.      */
  60.     @Override
  61.     public void onBackPressed() {
  62.         if (progressDialog != null && progressDialog.isShowing()) {
  63.             dismissDialog();
  64.         } else {
  65.             super.onBackPressed();
  66.         }
  67.     }
  68. }
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值