EditText 监听 Text 的 改动

[功能]
当EditText 的 Text 改变时 我们希望得到通知 但是可惜的是 android 并没有这个监听器 也就无从得知变化了 但是有个类可以帮助我们 那就是 TextWatcher


[前提]
现有 EditText 其id = edit.

[代码]
1. 定义 TextWatcher 的实例
Java代码
private TextWatcher watcher = new TextWatcher(){  
 
        @Override 
        public void afterTextChanged(Editable s) {  
            // TODO Auto-generated method stub  
              
        }  
 
        @Override 
        public void beforeTextChanged(CharSequence s, int start, int count,  
                int after) {  
            // TODO Auto-generated method stub  
              
        }  
 
        @Override 
        public void onTextChanged(CharSequence s, int start, int before,  
                int count) {  
            Log.d("TAG","[TextWatcher][onTextChanged]"+s);  
              
        }  
          
    }; 

private TextWatcher watcher = new TextWatcher(){

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

}

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

}

@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
Log.d("TAG","[TextWatcher][onTextChanged]"+s);

}
   
    };


2. 在 EditText 上注册该 TextWatcher 实例
Java代码
EditText et = (EditText)findViewById(R.id.edit);  
        et.addTextChangedListener(watcher); 

EditText et = (EditText)findViewById(R.id.edit);
        et.addTextChangedListener(watcher);

你可能感兴趣的:(android)