How do I display an alert dialog on Android?

后端 未结 30 2522
清歌不尽
清歌不尽 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:43

    showDialog(MainActivity.this, "title", "message", "OK", "Cancel", {...}, {...});
    

    Kotlin

    fun showDialog(context: Context, title: String, msg: String,
                   positiveBtnText: String, negativeBtnText: String?,
                   positiveBtnClickListener: DialogInterface.OnClickListener,
                   negativeBtnClickListener: DialogInterface.OnClickListener?): AlertDialog {
        val builder = AlertDialog.Builder(context)
                .setTitle(title)
                .setMessage(msg)
                .setCancelable(true)
                .setPositiveButton(positiveBtnText, positiveBtnClickListener)
        if (negativeBtnText != null)
            builder.setNegativeButton(negativeBtnText, negativeBtnClickListener)
        val alert = builder.create()
        alert.show()
        return alert
    }
    

    Java

    public static AlertDialog showDialog(@NonNull Context context, @NonNull String title, @NonNull String msg,
                                         @NonNull String positiveBtnText, @Nullable String negativeBtnText,
                                         @NonNull DialogInterface.OnClickListener positiveBtnClickListener,
                                         @Nullable DialogInterface.OnClickListener negativeBtnClickListener) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context)
                .setTitle(title)
                .setMessage(msg)
                .setCancelable(true)
                .setPositiveButton(positiveBtnText, positiveBtnClickListener);
        if (negativeBtnText != null)
            builder.setNegativeButton(negativeBtnText, negativeBtnClickListener);
        AlertDialog alert = builder.create();
        alert.show();
        return alert;
    }
    

提交回复
热议问题