【问题标题】:How to check if an EditText was changed or not?如何检查 EditText 是否已更改?
【发布时间】:2011-09-12 17:55:56
【问题描述】:

我需要知道 EditText 是否被更改,而不是用户是否在字段中输入了一些文本,而只需要知道 String 是否被更改。

【问题讨论】:

    标签: android android-edittext


    【解决方案1】:

    你需要一个 TextWatcher

    在这里查看它的实际效果:

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

    【讨论】:

      【解决方案2】:

      如果你改变主意听击键,你可以使用 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;
              }
          });
      

      但 Johe 的答案正是你所需要的。

      【讨论】:

        【解决方案3】:

        这实际上对我有用

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

        【讨论】:

          【解决方案4】:

          实现TextWatcher。它为您提供了三种方法,beforeTextChangedonTextChangedafterTextChanged。最后一个方法在发生变化之前不应该被调用,所以使用它是一件好事。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2018-04-17
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2010-11-06
            • 2020-01-03
            • 1970-01-01
            相关资源
            最近更新 更多