显示倒计时的Dialog

这里直接用系统Dialog中添加了倒计时的显示,如果用自定义Dialog会更美观;

 private TextView mOffTextView;
 private Handler mOffHandler;
 private Timer mOffTime;
 private Dialog mDialog;



//////创建对话框

void initDialog(){
  
   mOffTextView = new TextView(this);
  
   mDialog = new AlertDialog.Builder(this)
    .setTitle("提示")
         .setCancelable(false)
         .setView(mOffTextView) ////
         
         .setPositiveButton("确定", new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int id) {
           mOffTime.cancel();
           off();////关闭后的一些操作         
          }
         })
         .setNegativeButton("取消", new DialogInterface.OnClickListener() {
             public void onClick(DialogInterface dialog, int id) {
              dialog.cancel();
              mOffTime.cancel();
             }
         })
         .create();
   mDialog.show();
   mDialog.setCanceledOnTouchOutside(false);

    mOffHandler = new Handler() {
     public void handleMessage(Message msg) {

      if (msg.what > 0) {

        ////动态显示倒计时
       mOffTextView.setText("    即将关闭:"+msg.what);

      } else {
      ////倒计时结束自动关闭

       if(mDialog!=null){
        mDialog.dismiss();
       }
       off();////关闭后的操作

       mOffTime.cancel();
      }
      super.handleMessage(msg);
     }

    };

          //////倒计时

         mOffTime = new Timer(true);
      TimerTask tt = new TimerTask() {
       int countTime = 10;
       public void run() {
        if (countTime > 0) {
         countTime--;
        }
        Message msg = new Message();
        msg.what = countTime;
        mOffHandler.sendMessage(msg);
       }
      };
      mOffTime.schedule(tt, 1000, 1000);
     }


 

效果图

显示倒计时的Dialog_第1张图片

你可能感兴趣的:(Android,Android,Dialog,倒计时)