Producing a Dialog that will be dismissed automatically
is it possible to create a Dialog
that will be dismissed automatically after so开发者_JAVA百科me time if it doesn't have any user interaction?
You could use a Handler to automatically dismiss it.
In the class members:
private final int CANCEL_DIALOG = 1;
private Handler mHandler;
private Dialog mDialog;
In onCreate():
mHandler = new Handler(new Handler.Callback()
{
@Override
public boolean handleMessage(Message msg)
{
if(msg.what == CANCEL_DIALOG)
{
mDialog.cancel();
}
return false;
}
});
On the button you use to open the dialog (or whatever system you use):
mDialog.show();
mHandler.sendEmptyMessageDelayed(CANCEL_DIALOG, 5000);
Essentially after 5 seconds, the dialog will close after it has opened using this code.
I got it finally by using Handler
.
mHandler = new Handler(new Handler.Callback()
{
@Override
public boolean handleMessage(Message msg)
{
if(msg.what == CANCEL_DIALOG)
{
mDialog.cancel();
}
return false;
}
});
mDialog.show();
mHandler.sendEmptyMessageDelayed(CANCEL_DIALOG, 5000);
Inside Dialog
I have a ListView
. In the scrollListener
of that ListView
I put:
mHandler.removeMessages(CANCEL_DIALOG);
mHandler.sendEmptyMessageDelayed(CANCEL_DIALOG, 5000);
You can use an activity as dialog box and then finish it after some time(as you want).
dialog.show();
final Timer t = new Timer();
t.schedule(new TimerTask()
{
public void run()
{
dialog.dismiss(); // when the task active then close the dialog
t.cancel(); // also just top the timer thread,otherwise, you may receive a crash report
}
}, 2000);
You can use CountDownTimer
As simple as that.
new CountDownTimer(5000, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
//Your AlertDialog.cancel
dialog.cancel();
}
}.start();
final Timer t = new Timer();
t.schedule(new TimerTask() {
public void run() {
dlg.dismiss(); // when the task active then close the
// dialog(here we are dismissing the dialog)
t.cancel(); // also just top the timer thread,
// otherwise, you may receive a crash report
}
}, 2000);
Here we are creating the Timer object and scheduling the timer for 2 sec.once 2 sec over ,then it automatically calls run(), in run() we will write the logic to dismiss the dislog
精彩评论