Search code examples
androidandroid-dialogfragment

Keep DialogFragment open until user inputs are valid Android?


I subclass DialogFragment to show an input field to the user.

If the user does not provide any input I want to keep the dialog open and show an error on the input field. The dialog is dismissed automatically when the user press the positive "Save" button no matter if the input field is empty or not.

How can I override this default behaviour?

code snippet (full code is very long, but you get the idea):

public class SurveySingleQuestionDialog extends DialogFragment implements DialogInterface.OnClickListener {

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    return (builder.setTitle(mArgs.getString("question_body"))
            .setView(layout)
            .setPositiveButton(R.string.save, this)
            .setNegativeButton(android.R.string.cancel, null)
            .setCancelable(false)
            .show());

}

@Override
public void onClick(DialogInterface dialog, int which) {

if(validInputs()){

//dismiss dialog and save inputs

}
else{

//show error on input field

}

}

}

Any suggestion?


Solution

  • I think the setNegative / setPositive buttons are designed to dismiss the dialogue after the callback has returned. You would probably be better including your own buttons in your view and dismissing the dialogue yourself