How to check if an EditText was changed or not?

2019-01-18 03:09发布

I need to know if an EditText was changed or not, not whether or not the user inputted some text in the field, but only the if String was changed.

4条回答
ゆ 、 Hurt°
2楼-- · 2019-01-18 03:29

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) {

  }
}
查看更多
女痞
3楼-- · 2019-01-18 03:32

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.

查看更多
虎瘦雄心在
4楼-- · 2019-01-18 03:36

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.

查看更多
Root(大扎)
5楼-- · 2019-01-18 03:38

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) {

    }
});
查看更多
登录 后发表回答