根据editText值关闭对话框

时间:2015-03-06 23:40:49

标签: android alertdialog dismiss

我在EditText内有一个AlertDialog。我希望只要在EditText中检测到“停止”一词,就会解除对话框。我尝试在对话框上调用dismiss(),但它不起作用:

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();

有什么想法解决这个问题吗?

1 个答案:

答案 0 :(得分:2)

对话框popup不是显示的对话框。您创建它,然后在调用show()时创建另一个完全不同的对话框。尝试直接在弹出窗口上调用命令:

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();