AlertDialog - how can I run checks when user hits 'OK'

后端 未结 4 1820
鱼传尺愫
鱼传尺愫 2021-01-13 14:46

For a custom AlertDialog, can I override the positive button to NOT close the dialog? instead I want to run some edit checks and keep the dialog open if my checks fail.

4条回答
  •  [愿得一人]
    2021-01-13 14:53

    Here's how I did it. Technically, it doesn't technically keep the dialog open, it closes it momentarily and re-opens it, but the net result is the same.

    class MyAlertDialog implements OnDismissListener, OnCancelListener {
        final private EditText editText;
        final private AlertDialog alertDialog;
        final private EventManager eventManager;
        final private CategorySelector categorySelector;
    
        private Boolean canceled;
    
        MyAlertDialog(Context context) {
            editText = new EditText(context);
            alertDialog = buildAlertDialog(context);
            alertDialog.setOnDismissListener(this);
            alertDialog.setOnCancelListener(this);
            show();
        }
    
        private AlertDialog buildAlertDialog(Context context) {
            return new AlertDialog.Builder(context)
            .setTitle(context.getString(R.string.enter_name))
            .setMessage(context.getString(R.string.enter_name))
            .setView(editText)
            .setNeutralButton(context.getString(R.string.save_text), null)
            .setNegativeButton(context.getString(R.string.cancel_text), null).create();
        }
    
        public void show() {
            canceled = false;
            alertDialog.show();
        }
    
        @Override
        public void onDismiss(DialogInterface dialog) {
            if(!canceled) {
                final String name = editText.getText().toString();
                if(name.equals("")) {
                    editText.setError("Please enter a non-empty name");
                    show();
                } else {
                    doWhateverYouWantHere(name);
                }
            }
        }
    
        @Override
        public void onCancel(DialogInterface dialog) {
            canceled = true;
        }
    }
    

提交回复
热议问题