How do I display an alert dialog on Android?

后端 未结 30 2532
清歌不尽
清歌不尽 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: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();
    }
    

提交回复
热议问题