对话框未在Android中显示

时间:2013-03-13 19:31:23

标签: java android android-alertdialog

我有一些特定的逻辑,需要在解除微调器并显示对话框消息之前等待5秒。一切正常但对话框信息未显示。如果我毫不拖延地做同样的事情就行了。 我的代码是:

public static void showMessageNotSentDialog(Activity inActivity)
{
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(inActivity);                       
    alertDialogBuilder.setTitle(R.string.error);         

    alertDialogBuilder.setMessage(R.string.error_sending_message);
    alertDialogBuilder.setCancelable(false);

    alertDialogBuilder.setPositiveButton(R.string.ok,new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog,int id) {
        }

    });

    AlertDialog alertDialog = alertDialogBuilder.create();      
    alertDialog.show();
}

public static void showDelayedErrorMessage(final Activity inActivity)
{

    Runnable task = new Runnable() {
        public void run() {
            com.test.classes.Spinner.hideSpinner();
            showMessageNotSentDialog(inActivity);

      }
      worker.schedule(task, com.test.classes.Spinner.TEXT_SPINNER_HIDEOUT_SEC, TimeUnit.SECONDS);
}

尝试从UI线程显示对话框:

public static void showDelayedErrorMessage(final Activity inActivity)
{

    Runnable task = new Runnable() {
        public void run() {
            com.test.classes.Spinner.hideSpinner();

            Runnable messageTask = new Runnable() {
                public void run() {
                    showMessageNotSentDialog(inActivity);
                }
              };
              inActivity.runOnUiThread(messageTask);
        }
      };

      worker.schedule(task, com.test.classes.Spinner.TEXT_SPINNER_HIDEOUT_SEC, TimeUnit.SECONDS);         
}

2 个答案:

答案 0 :(得分:1)

你应该使用Handler,它可以更新gui线程。基本上你可以在延迟处理器上发布执行,这是一个例子:

Handler guiHandler = new Handler();
Runnable showDialog = new Runnable(){
   public void run(){
     //put here the dialog creation
   }
}

postDelayed (showDialog ,5000); // Post for 5 seconds

请注意,Handler的创建必须在GUI线程内,否则将无法工作。并记住GUI只能由主线程操作。

答案 1 :(得分:1)

使用倒计时器,无需使用线程

    new CountDownTimer(5000,5000) {

        @Override
        public void onTick(long arg0) {

        }

        @Override
        public void onFinish() {

        }
    }.start();

onfinish在5秒后执行