Search code examples
androidandroid-dialogandroid-dialogfragment

Dialog.setOnShowListener() alternative for API level < 8


I have an AlertDialog implemented via DialogFragment.onCreateDialog(). The dialog has an EditText and two buttons, OK and Cancel. When the OK button is clicked I need to do some checking on the content of the EditText: if the content is wrong the dialog shouldn't be dismissed. Searching on SO I've seen that this functionality can be easily achieved this way:

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    view = getActivity().getLayoutInflater().inflate(AD_LAYOUT, null);
    mEditText = (EditText) view.findViewById(AD_VIEW);
    myAlertDialog = new AlertDialog.Builder(getActivity())
    .setView(view)
    .setTitle(getResources().getString(AD_TITLE))
    .setPositiveButton(getResources().getString(AD_PB),
            new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int buttonID) {
            //Do nothing. We are going to override this method
        }
    })
    .setNegativeButton(getResources().getString(AD_NB),
            new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int buttonID) {
            ((MainActivity)getActivity()).doNegative(NewGalleryDlg.this);
        }
    })
    .create();
    ad = myAlertDlg;

    ad.setOnShowListener(new DialogInterface.OnShowListener() {
        @Override
        public void onShow(DialogInterface dialog) {
            Button b = ad.getButton(AlertDialog.BUTTON_POSITIVE);
            b.setOnClickListener(new View.OnClickListener(){
                @Override public void onClick(View view) {
                    ((MainActivity)getActivity())
                    .doPositive(NewGalleryDlg.this, mEditText);
                }
            });
        }
    });
    return ad;
}

The problem is that I'm using the Support Library v4 but the setOnShowListener() requires API level 8 or higher. Could someone give me an alternative? TIA


Solution

  • OK, finally I solved it using a different approach. Instead of using AlertDialog.setOnShowListener() (which works fine if API level > 7) I've added a validator to the EditText of my AlertDialog. If the entered text is invalid then the OK button gets disabled.

    The implementation steps are:

    • make the activity to implement the TextWatcher interface
    • the afterTextChanged() contains the code that does the validation and enable/disable the OK button
    • in the DialogFragment.onCreateDialog() add the TextChanged listener to the EditText (see below)

    That's all. It works like a charm now.

    mEditText.addTextChangedListener((MainActivity)getActivity());