How can I reuse an AlertDialog for Yes/No on Android?

前端 未结 2 1056
说谎
说谎 2021-02-04 18:49

I\'m trying to find the way to reuse a Dialog that shows customized titles, then send the Yes/No click to the function that has launched the Dialog.

I have two buttoms,

2条回答
  •  温柔的废话
    2021-02-04 19:36

    Complete solution Try this

    1) Createa Interface

    import android.content.DialogInterface;
    
    public interface AlertMagnatic {
    
        public abstract void PositiveMethod(DialogInterface dialog, int id);
        public abstract void NegativeMethod(DialogInterface dialog, int id);
    }
    

    2) Generalize method for confirm dialog.

    public static void getConfirmDialog(Context mContext,String title, String msg, String positiveBtnCaption, String negativeBtnCaption, boolean isCancelable, final AlertMagnatic target) {
            AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
    
            int imageResource = android.R.drawable.ic_dialog_alert;
            Drawable image = mContext.getResources().getDrawable(imageResource);
    
            builder.setTitle(title).setMessage(msg).setIcon(image).setCancelable(false).setPositiveButton(positiveBtnCaption, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    target.PositiveMethod(dialog, id);
                }
            }).setNegativeButton(negativeBtnCaption, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {
                    target.NegativeMethod(dialog, id);
                }
            });
    
            AlertDialog alert = builder.create();
            alert.setCancelable(isCancelable);
            alert.show();
            if (isCancelable) {
                alert.setOnCancelListener(new OnCancelListener() {
    
                    @Override
                    public void onCancel(DialogInterface arg0) {
                        target.NegativeMethod(null, 0);
                    }
                });
            }
        }
    

    3) How to use

    getConfirmDialog(getString(R.string.logout), getString(R.string.logout_message), getString(R.string.yes), getString(R.string.no), false,
                    new AlertMagnatic() {
    
                        @Override
                        public void PositiveMethod(final DialogInterface dialog, final int id) {}
    
                        @Override
                        public void NegativeMethod(DialogInterface dialog, int id) {
    
                        }
                    });
    

提交回复
热议问题