Home > OS >  AlertDialog.Builder won't show after create()
AlertDialog.Builder won't show after create()

Time:11-26

I'm making a dialog that shows current progress and dismiss after 1 second for experiment. The following code did show the dialog.

/** Show progress dialog */
public static View showProgressDialog(Context context) {
    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
    View dialogView = inflater.inflate(R.layout.window_progress_dialog, null);

    builder.setTitle(R.string.msg_progress_loading);
    builder.setView(dialogView);
    builder.setCancelable(false);

    builder.setPositiveButton(null, null);
    builder.show();

    return dialogView;
}

But if I make it like this, the dialog don't show.

/** Show progress dialog */
public static View showProgressDialog(Context context) {
    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
    View dialogView = inflater.inflate(R.layout.window_progress_dialog, null);

    builder.setTitle(R.string.msg_progress_loading);
    builder.setView(dialogView);
    builder.setCancelable(false);

    builder.setPositiveButton(null, null);
    final AlertDialog alertDialog = builder.show();
    new Handler().post(new Runnable() {
        @Override
        public void run() {
            SystemClock.sleep(1000);
            alertDialog.dismiss();
        }
    });

    return dialogView;
}

Am I missing something?

CodePudding user response:

Any task that you are posting to a Handler is running on the Main/UI thread. So when you call sleep() on it the entire UI thread (which is responsible for showing the dialog) stops for a second.

So, use Handler.postDelayed() instead.

new Handler().postDelayed(new Runnable() {
     @Override
     public void run() {
         alertDialog.dismiss();
     }
}, 1000); //milliseconds

Here, you are telling the main thread to dismiss the dialog, but you are telling it after 1 second (delayed). This may not work on all devices as the UI thread may take more than a second to show the dialog in devices with low performance. So consider increasing the delay time.

  • Related