当前位置: 动力学知识库 > 问答 > 编程问答 >

android - Dismiss a dialog based on editText value

问题描述:

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 ?

网友答案:

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();
分享给朋友:
您可能感兴趣的文章:
随机阅读: