Android对话框定时自动关闭的实现

来源:互联网 发布:杭州软件测试在职培训 编辑:程序博客网 时间:2024/05/18 00:19

下面,我们使用一般的对话框AlertDialog来举例:

1、首先,在类(SampleView)内定义一个对话框,而后在需要弹出对话框的时候,进行赋值:

private AlertDialog alertDialog = null;//私有的对话框  

2、声明并定义一个计时器,并在定时器内定义标志位,用于对传递消息进行判断:

private final int CLOSE_ALERTDIALOG = 0;  //定义关闭对话框的动作信号标志  private final int CLOSE_SAMPLE_VIEW = 0;  //定义关闭SampleView的动作信号标志         private DelayCloseController delayCloseController = new DelayCloseController();  private class DelayCloseController extends TimerTask {      private Timer timer = new Timer();                 private int actionFlags = 0;//标志位参数                 public void setCloseFlags(int flag)          {              actionFlags = flag;          }      @Override      public void run() {          Message messageFinish = new Message();          messageFinish.what = actionFlags ;          mHandler.sendMessage(messageFinish);      }  }  

3、声明并定义一个Handler,用于接收定时器发送的信息,并对信息作出反馈。

private Handler mainHandler = new Handler(){      @Override      public void handleMessage(Message msg) {          switch (msg.what) {          case CLOSE_SAMPLE_VIEWER:              if(alertDialog != null && alertDialog.isShowing())              {                  alertDialog.dismiss();              }              SampleView.this.finish();              break;          case CLOSE_ALERTDIALOG:              if(alertDialog != null alertDialog.isShowing())              {                  alertDialog.dismiss();  //关闭对话框              }              break;          default:              break;          }      }     };  

4、上述动作,已经完成了我们需要为程序做的准备工作,接下来,只需在需要弹出对话框的位置添加对话框定义并显示的代码,以及发送相关的消息即可:

//初始化对话框并显示         alertDialog = new AlertDialog.Builder(Main.this)  .setTitle("自动关闭对话框")  .setMessage("对话框将在8s之后关闭")  .show();         delayCloseController.setCloseFlags(CLOSE_ALERTDIALOG);             //设置信息标志位         delayCloseController.timer.schedule(delayCloseController, 8000);   //启动定时器  

依照以上的方法即可实现对话框的定时关闭的功能了。

0 0