如何在用户在Android编辑文本中输入字符时触发事件?

时间:2013-05-06 05:20:26

标签: android android-edittext

在我的android项目中。我想在用户输入特定字符时触发事件(显示对话框)(例如:当用户输入“s”时)。我试过文本观察者,但对话框显示两次

请任何人帮助我

添加了代码

mText.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {
            // TODO Auto-generated method stub
            if (s.charAt(s.length() - 1) == 's') {

                dialog.show();
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub

        }
    });

1 个答案:

答案 0 :(得分:0)

您可以添加TextWatcher,如下所示:

 yourTextView.addTextChangedListener(new TextWatcher() {
     @Override
     public void onTextChanged(CharSequence s, int start, int before, int count) {
     }

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

     @Override
     public void afterTextChanged(Editable editable) {
      //handle the text changed
     }
 });