How to check if an EditText was changed or not?

早过忘川 提交于 2019-11-28 09:02:51
j7nn7k

You need a TextWatcher

See it here in action:

EditText text = (EditText) findViewById(R.id.YOUR_ID);
text.addTextChangedListener(textWatcher);


private TextWatcher textWatcher = new TextWatcher() {

  public void afterTextChanged(Editable s) {
  }

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

  public void onTextChanged(CharSequence s, int start, int before,
          int count) {

  }
}

If you change your mind to listen to the keystrokes you can use OnKeyListener

    EditText et = (EditText) findViewById(R.id.search_box); 

    et.setOnKeyListener(new View.OnKeyListener() {

        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            //key listening stuff
            return false;
        }
    });

But Johe's answer is what you need.

Implement a TextWatcher. It gives you three methods, beforeTextChanged, onTextChanged, and afterTextChanged. The last method shouldn't be called until something changes anyway, so that's a good thing to use for it.

Shreyas Sanil

This actually worked for me

EditText text = (EditText) findViewById(R.id.YOUR_ID);

text.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

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

        if(your_string.equals(String.valueOf(s))) {
           //do something
        }else{
            //do something 
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!