39

我正在开发一个无障碍应用程序。当用户想要离开应用程序时,我会显示一个对话框,他必须在其中确认他想要离开,如果他在 5 秒后没有确认,对话框应该会自动关闭(因为用户可能不小心打开了它)。这类似于您更改屏幕分辨率时在 Windows 上发生的情况(会出现警告,如果您不确认,它会恢复到以前的配置)。

这就是我显示对话框的方式:

AlertDialog.Builder dialog = new AlertDialog.Builder(this).setTitle("Leaving launcher").setMessage("Are you sure you want to leave the launcher?");
            dialog.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int whichButton) {
                    exitLauncher();
                }
            });
            dialog.create().show();

如何在显示 5 秒后关闭对话框?

4

9 回答 9

92
final AlertDialog.Builder dialog = new AlertDialog.Builder(this).setTitle("Leaving launcher").setMessage("Are you sure you want to leave the launcher?");
dialog.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int whichButton) {
        exitLauncher();
    }
});     
final AlertDialog alert = dialog.create();
alert.show();

// Hide after some seconds
final Handler handler  = new Handler();
final Runnable runnable = new Runnable() {
    @Override
    public void run() {
        if (alert.isShowing()) {
            alert.dismiss();
        }
    }
};

alert.setOnDismissListener(new DialogInterface.OnDismissListener() {
    @Override
    public void onDismiss(DialogInterface dialog) {
        handler.removeCallbacks(runnable);
    }
});

handler.postDelayed(runnable, 10000);
于 2013-01-21T19:38:59.357 回答
22

使用CountDownTimer来实现。

      final AlertDialog.Builder dialog = new AlertDialog.Builder(this)
            .setTitle("Leaving launcher").setMessage(
                    "Are you sure you want to leave the launcher?");
       dialog.setPositiveButton("Confirm",
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int whichButton) {
                     exitLauncher();

                }
            });
    final AlertDialog alert = dialog.create();
    alert.show();

    new CountDownTimer(5000, 1000) {

        @Override
        public void onTick(long millisUntilFinished) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onFinish() {
            // TODO Auto-generated method stub

            alert.dismiss();
        }
    }.start();
于 2013-01-21T19:38:04.130 回答
8

迟了,但我认为这可能对任何在他们的应用程序中使用 RxJava 的人有用。

RxJava 带有一个称为操作符的操作符.timer(),它将创建一个 Observable,它onNext()只会在给定的持续时间后触发一次,然后调用onComplete(). 这非常有用,并且避免了必须创建 Handler 或 Runnable。

更多关于这个操作符的信息可以在ReactiveX 文档中找到

// Wait afterDelay milliseconds before triggering call
Subscription subscription = Observable
        .timer(5000, TimeUnit.MILLISECONDS) // 5000ms = 5s
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Action1<Long>() {
            @Override
            public void call(Long aLong) {
                // Remove your AlertDialog here
            }
        });

您可以通过在单击按钮时取消订阅 observable 来取消计时器触发的行为。因此,如果用户手动关闭警报,调用subscription.unsubscribe()它具有取消计时器的效果。

于 2016-09-01T17:07:29.993 回答
7

这是代码,请参阅此链接

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // get button
        Button btnShow = (Button)findViewById(R.id.showdialog);
        btnShow.setOnClickListener(new View.OnClickListener() {
            //on click listener
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
                builder.setTitle("How to close alertdialog programmatically");
                builder.setMessage("5 second dialog will close automatically");
                builder.setCancelable(true);

                final AlertDialog closedialog= builder.create();

                closedialog.show();

                final Timer timer2 = new Timer();
                timer2.schedule(new TimerTask() {
                    public void run() {
                        closedialog.dismiss(); 
                        timer2.cancel(); //this will cancel the timer of the system
                    }
                }, 5000); // the timer will count 5 seconds....

            }
        });
    }
}

快乐编码!

于 2015-09-28T15:16:17.597 回答
3
AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(R.string.game_message);
        game_message = builder.create();
        game_message.show();


        final Timer t = new Timer();
        t.schedule(new TimerTask() {
            public void run() {
                game_message.dismiss(); // when the task active then close the dialog
                t.cancel(); // also just top the timer thread, otherwise, you may receive a crash report
            }
        }, 5000);

参考:https ://xjaphx.wordpress.com/2011/07/13/auto-close-dialog-after-a-specific-time/

于 2018-11-19T20:28:53.867 回答
3

对于受 Tahirhan 回答启发的 Kotlin。这对我当前的项目有效。希望它会在不久的将来对其他人有所帮助。我在片段中调用此函数。快乐编码!

 fun showAlert(message: String) {
        val builder = AlertDialog.Builder(activity)
        builder.setMessage(message)

        val alert = builder.create()
        alert.show()

        val timer = Timer()
        timer.schedule(object : TimerTask() {
            override fun run() {
                alert.dismiss()
                timer.cancel()
            }
        }, 5000)
    }
于 2020-06-23T06:17:53.270 回答
1

我在AlertDialog.

AlertDialog dialog = new AlertDialog.Builder(getContext())
        .setTitle(R.string.display_locked_title)
        .setMessage(R.string.display_locked_message)
        .setPositiveButton(R.string.button_dismiss, null)
        .create();

dialog.setOnShowListener(new DialogInterface.OnShowListener() {
    @Override
    public void onShow(DialogInterface dialog) {
        final Button positiveButton = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE);
        final CharSequence positiveButtonText = positiveButton.getText();
        new CountDownTimer(AUTO_DISMISS_MILLIS, 100) {
            @Override
            public void onTick(long millisUntilFinished) {
                positiveButton.setText(String.format(Locale.getDefault(), "%s (%d)",
                        positiveButtonText,
                        TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) + 1));
            }

            @Override
            public void onFinish() {
                dismiss();
            }
        }.start();

    }
});
于 2017-07-03T17:32:57.197 回答
0
showDialog(
    context: context,
    builder: (BuildContext context) {
        return AlertDialog(
            content: Text("Sucess"),
        );

    });
    Timer(Duration(seconds: 2),()=>Navigator.pop(context));
于 2021-11-22T11:45:10.523 回答
-6
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();

然后调用dismiss meth它工作

alertDialog .dismiss(); 
于 2015-10-15T09:40:46.757 回答