How do I display an alert dialog on Android?

后端 未结 30 2367
清歌不尽
清歌不尽 2020-11-22 03:02

I want to display a dialog/popup window with a message to the user that shows \"Are you sure you want to delete this entry?\" with one button that says \'Delete\'. When

相关标签:
30条回答
  • 2020-11-22 03:23
       new AlertDialog.Builder(v.getContext()).setMessage("msg to display!").show();
    
    0 讨论(0)
  • 2020-11-22 03:25

    This is definitely help for you. Try this code: On click of a button, you can put one, two or three buttons with an alert dialog...

    SingleButtton.setOnClickListener(new View.OnClickListener() {
    
        public void onClick(View arg0) {
            // Creating alert Dialog with one Button
    
            AlertDialog alertDialog = new AlertDialog.Builder(AlertDialogActivity.this).create();
    
            // Setting Dialog Title
            alertDialog.setTitle("Alert Dialog");
    
            // Setting Dialog Message
            alertDialog.setMessage("Welcome to Android Application");
    
            // Setting Icon to Dialog
            alertDialog.setIcon(R.drawable.tick);
    
            // Setting OK Button
            alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
    
                public void onClick(DialogInterface dialog,int which)
                {
                    // Write your code here to execute after dialog    closed
                    Toast.makeText(getApplicationContext(),"You clicked on OK", Toast.LENGTH_SHORT).show();
                }
            });
    
            // Showing Alert Message
            alertDialog.show();
        }
    });
    
    btnAlertTwoBtns.setOnClickListener(new View.OnClickListener() {
    
        public void onClick(View arg0) {
            // Creating alert Dialog with two Buttons
    
            AlertDialog.Builder alertDialog = new AlertDialog.Builder(AlertDialogActivity.this);
    
            // Setting Dialog Title
            alertDialog.setTitle("Confirm Delete...");
    
            // Setting Dialog Message
            alertDialog.setMessage("Are you sure you want delete this?");
    
            // Setting Icon to Dialog
            alertDialog.setIcon(R.drawable.delete);
    
            // Setting Positive "Yes" Button
            alertDialog.setPositiveButton("YES",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,int which) {
                            // Write your code here to execute after dialog
                            Toast.makeText(getApplicationContext(), "You clicked on YES", Toast.LENGTH_SHORT).show();
                        }
                    });
    
            // Setting Negative "NO" Button
            alertDialog.setNegativeButton("NO",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,    int which) {
                            // Write your code here to execute after dialog
                            Toast.makeText(getApplicationContext(), "You clicked on NO", Toast.LENGTH_SHORT).show();
                            dialog.cancel();
                        }
                    });
    
            // Showing Alert Message
            alertDialog.show();
        }
    });
    
    btnAlertThreeBtns.setOnClickListener(new View.OnClickListener() {
    
        public void onClick(View arg0) {
            // Creating alert Dialog with three Buttons
    
            AlertDialog.Builder alertDialog = new AlertDialog.Builder(
                    AlertDialogActivity.this);
    
            // Setting Dialog Title
            alertDialog.setTitle("Save File...");
    
            // Setting Dialog Message
            alertDialog.setMessage("Do you want to save this file?");
    
            // Setting Icon to Dialog
            alertDialog.setIcon(R.drawable.save);
    
            // Setting Positive Yes Button
            alertDialog.setPositiveButton("YES",
                new DialogInterface.OnClickListener() {
    
                    public void onClick(DialogInterface dialog,
                            int which) {
                        // User pressed Cancel button. Write Logic Here
                        Toast.makeText(getApplicationContext(),
                                "You clicked on YES",
                                Toast.LENGTH_SHORT).show();
                    }
                });
    
            // Setting Negative No Button... Neutral means in between yes and cancel button
            alertDialog.setNeutralButton("NO",
                new DialogInterface.OnClickListener() {
    
                    public void onClick(DialogInterface dialog,
                            int which) {
                        // User pressed No button. Write Logic Here
                        Toast.makeText(getApplicationContext(),
                                "You clicked on NO", Toast.LENGTH_SHORT)
                                .show();
                    }
                });
    
            // Setting Positive "Cancel" Button
            alertDialog.setNegativeButton("Cancel",
                new DialogInterface.OnClickListener() {
    
                    public void onClick(DialogInterface dialog,
                            int which) {
                        // User pressed Cancel button. Write Logic Here
                        Toast.makeText(getApplicationContext(),
                                "You clicked on Cancel",
                                Toast.LENGTH_SHORT).show();
                    }
                });
            // Showing Alert Message
            alertDialog.show();
        }
    });
    
    0 讨论(0)
  • 2020-11-22 03:25

    I'd like to add on David Hedlund great answer by sharing a more dynamic method than what he posted so it can be used when you do have a negative action to perform and when you don't, i hope it helps.

    private void showAlertDialog(@NonNull Context context, @NonNull String alertDialogTitle, @NonNull String alertDialogMessage, @NonNull String positiveButtonText, @Nullable String negativeButtonText, @NonNull final int positiveAction, @Nullable final Integer negativeAction, @NonNull boolean hasNegativeAction)
    {
        AlertDialog.Builder builder;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            builder = new AlertDialog.Builder(context, android.R.style.Theme_Material_Dialog_Alert);
        } else {
            builder = new AlertDialog.Builder(context);
        }
        builder.setTitle(alertDialogTitle)
                .setMessage(alertDialogMessage)
                .setPositiveButton(positiveButtonText, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        switch (positiveAction)
                        {
                            case 1:
                                //TODO:Do your positive action here 
                                break;
                        }
                    }
                });
                if(hasNegativeAction || negativeAction!=null || negativeButtonText!=null)
                {
                builder.setNegativeButton(negativeButtonText, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        switch (negativeAction)
                        {
                            case 1:
                                //TODO:Do your negative action here
                                break;
                            //TODO: add cases when needed
                        }
                    }
                });
                }
                builder.setIcon(android.R.drawable.ic_dialog_alert);
                builder.show();
    }
    
    0 讨论(0)
  • 2020-11-22 03:26

    The code which David Hedlund has posted gave me the error:

    Unable to add window — token null is not valid

    If you are getting the same error use the below code. It works!!

    runOnUiThread(new Runnable() {
        @Override
        public void run() {
    
            if (!isFinishing()){
                new AlertDialog.Builder(YourActivity.this)
                  .setTitle("Your Alert")
                  .setMessage("Your Message")
                  .setCancelable(false)
                  .setPositiveButton("ok", new OnClickListener() {
                      @Override
                      public void onClick(DialogInterface dialog, int which) {
                          // Whatever...
                      }
                  }).show();
            }
        }
    });
    
    0 讨论(0)
  • 2020-11-22 03:27

    This is done in kotlin

    val builder: AlertDialog.Builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog_Alert)
            } else {
                AlertDialog.Builder(this)
            }
            builder.setTitle("Delete Alert!")
                    .setMessage("Are you want to delete this entry?")
                    .setPositiveButton("YES") { dialog, which ->
    
                    }
                    .setNegativeButton("NO") { dialog, which ->
    
                    }
                    .setIcon(R.drawable.ic_launcher_foreground)
                    .show()
    
    0 讨论(0)
  • 2020-11-22 03:28

    You could use an AlertDialog for this and construct one using its Builder class. The example below uses the default constructor that only takes in a Context since the dialog will inherit the proper theme from the Context you pass in, but there's also a constructor that allows you to specify a specific theme resource as the second parameter if you desire to do so.

    new AlertDialog.Builder(context)
        .setTitle("Delete entry")
        .setMessage("Are you sure you want to delete this entry?")
    
        // Specifying a listener allows you to take an action before dismissing the dialog.
        // The dialog is automatically dismissed when a dialog button is clicked.
        .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) { 
                // Continue with delete operation
            }
         })
    
        // A null listener allows the button to dismiss the dialog and take no further action.
        .setNegativeButton(android.R.string.no, null)
        .setIcon(android.R.drawable.ic_dialog_alert)
        .show();
    
    0 讨论(0)
提交回复
热议问题