Add a delay to Progress Dialog
I want to make a dummy progress dialog appear for 2 or 3 seconds开发者_如何学运维. It won't actually do anything other than say detecting. I have the code:
ProgressDialog dialog = ProgressDialog.show(this, "", "Detecting...",
true);
dialog.show();
dialog.dismiss();
But what do I put in between the show, and the dismissal to have the dialog appear for a few seconds? Thanks!
The correct way - it does not block your main thread, so UI stays responsive:
dialog.show();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
dialog.dismiss();
}
}, 3000); // 3000 milliseconds delay
progress.setProgress(100);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
pdialog.dismiss();
}}, 3000);
You can also use CountDownTimer
of Android which is much more efficient than any other solution posted and it also support fires on regular interval through its onTick()
method.
Have a look at this example,
new CountDownTimer(3000, 1000) {
public void onTick(long millisUntilFinished) {
// You don't need anything here
}
public void onFinish() {
dialog.dismiss();
}
}.start();
You can do something like this:
new AsyncTask<Void, Void, Void>
{
ProgressDialog dialog = new ProgressDialog(MainActivity.this);
@Override
protected void onPreExecute() {
super.onPreExecute();
dialog.setTitle("Please wait");
dialog.setMessage("Preparing resources...");
dialog.setCancelable(false);
dialog.show();
}
@Override
protected Void doInBackground(Void... params) {
try{
Thread.sleep(3000);
}
catch(Exception e)
{
e.printStackTrace();
}
}
@Override
protected void onPostExecute(Void aVoid)
{
super.onPostExecute(aVoid);
if (dialog!=null && dialog.isShowing())
{
dialog.dismiss();
}
}
}.execute();
Nothing comes between dismiss and show.. the time depending upon you. For example dialog will show before server access and it will dismiss getting result means
dialog.show();
ServerCall();
dialog.close();
If you need empty delay means then use CountDownTimer call between that..
In case some one looking for Xamarin.Android
(using C#) solution (of Peter Knego's answer), here is how:
new Handler().PostDelayed(() => {
dialog.dismiss();
}, 1000);
精彩评论