要实现该接口必须重写beforeTextChanged,onTextChanged,afterTextChanged三种方法,
package com.ray.anynew; import android.app.Activity; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.widget.EditText; import android.widget.TextView; import com.example.edittextlistener.R; public class MainActivity extends Activity { private EditText input; private TextView display; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //调用布局文件 initView(); //初始化操作 } private void initView() { input = (EditText)findViewById(R.id.input); display = (TextView)findViewById(R.id.display); //设置EditText监听事件 input.addTextChangedListener(new myTextWatcher()); } /** * * myTextWatcher实行TextWatcher * 接口并重写以下三种方法 * @author anynew * */ class myTextWatcher implements 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) { //当文本正在改变时执行 } @Override public void afterTextChanged(Editable s) { /* 统计字母数字个数 int count = 0; for(int i=0;i<s.length();i++){ char cs =s.charAt(i); if((cs>='a'&& cs<='z') || ((cs>='A'&& cs<='Z')) || ((cs>='0'&& cs<='9')) ){ count++; } } display.setText("当前输入的文字个数:"+count); */ //统计汉字的个数 int count =0; String Reg="^[\u4e00-\u9fa5]{1}$"; //汉字的正规表达式 for(int i=0;i<s.length();i++){ String b=Character.toString(s.charAt(i)); if(b.matches(Reg)) count++; } //设置文本内容 display.setText("当前输入的文字个数:"+count); } } }