0

I have an EditText inside an AlertDialog. I would like the dialog to be dismissed whenever the word "stop" is detected in the EditText. I tried calling dismiss()on the dialog, but it doesn't work :

AlertDialog.Builder builder = new AlertDialog.Builder(this);
final Dialog popup = builder.create();
final EditText edit = new EditText(this);
edit.setGravity(Gravity.CENTER);
edit.addTextChangedListener(new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence pRequest, int start, int before, int count) {

    }

    @Override
    public void beforeTextChanged(CharSequence pRequest, int start, int count, int after) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        String currentText = s.toString().toLowerCase();
        if (currentText.contains("stop")) {
            InputMethodManager imm = (InputMethodManager)getSystemService(
                      Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(edit.getWindowToken(), 0); // Hide keyboard
            popup.dismiss();
        }

    }

});
builder.setTitle("Value")
.setView(edit)
.show();

Any idea to fix this ?

3kt
  • 2,543
  • 1
  • 17
  • 29

1 Answers1

2

The dialog popup is not the dialog shown. You create it, and then create another COMPLETELY DIFFERENT dialog when calling show(). Try calling the commands on popup directly:

AlertDialog.Builder builder = new AlertDialog.Builder(this);
final Dialog popup = builder.create();
final EditText edit = new EditText(this);
edit.setGravity(Gravity.CENTER);
edit.addTextChangedListener(new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence pRequest, int start, int before, int count) {

    }

    @Override
    public void beforeTextChanged(CharSequence pRequest, int start, int count, int after) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        String currentText = s.toString().toLowerCase();
        if (currentText.contains("stop")) {
            InputMethodManager imm = (InputMethodManager)getSystemService(
                      Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(edit.getWindowToken(), 0); // Hide keyboard
            popup.dismiss();
        }

    }

});
popup.setTitle("Value");
popup.setView(edit);
popup.show();
SilverCorvus
  • 2,956
  • 1
  • 15
  • 26