Android Confirmation dialog returning true or false

前端 未结 8 1274
不知归路
不知归路 2020-12-09 05:40

It seems to be there is no easy way to get an Alert dialog to return a simple value.
This code does not work (the answer variable cannot be set

8条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-09 06:00

    I find that using jDeferred helps in cases where you want to wait for input.

    It is essentially equivalent to using an interface, but instead you create done and fail handlers. Just an alternative to consider:

    new ConfirmationDialog(mContext)
            .showConfirmation("Are you sure?", "Yes", "No")
            .done(new DoneCallback() {
                @Override
                public void onDone(Void aVoid) {
                    ....
                }
            })
            .fail(new FailCallback() {
    
                @Override
                public void onFail(Void aVoid) {
                    ...
                }
            });
    

    Implementation:

    public class ConfirmationDialog {
    
    
        private final Context mContext;
        private final DeferredObject mDeferred = new DeferredObject();
    
        public ConfirmationDialog(Context context) {
            mContext = context;
        }
    
        public Promise showConfirmation(String message, String positiveButton, String negativeButton) {
            AlertDialog dialog = new AlertDialog.Builder(mContext).create();
            dialog.setTitle("Alert");
            dialog.setMessage(message);
            dialog.setCancelable(false);
            dialog.setButton(DialogInterface.BUTTON_POSITIVE, positiveButton, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int buttonId) {
                    mDeferred.resolve(null);
                }
            });
            dialog.setButton(DialogInterface.BUTTON_NEGATIVE, negativeButton, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int buttonId) {
                    mDeferred.reject(null);
                }
            });
            dialog.setIcon(android.R.drawable.ic_dialog_alert);
            dialog.show();
            return mDeferred.promise();
        }
    
    }
    

提交回复
热议问题