When an object of a type is attached to an Editable, its methods will be called when the text is changed.
當一個可編輯的對象的文本改變的時候,它的方法就會被調用。
此接口有三個方法
This
method is called to notify you that, somewhere within s
,
the text has been changed.
當s的某個位置的文本已經改變,這個方法會被調用
beforeTextChanged(CharSequence s, int start, int count, int after)
This
method is called to notify you that, within s
,
the count
characters
beginning at start
are
about to be replaced by new text with length after
.
在s中,當從start開始的count個字符將被長度爲after的新文本替換時,這個方法會被調用
onTextChanged(CharSequence s, int start, int before, int count)
This
method is called to notify you that, within s
,
the count
characters
beginning at start
have
just replaced old text that had length before
.
在s中,當從start開始有count個字符替換長度爲before的舊文本時,這個方法會被調用
下面是一個限制輸入"."個數的例子
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
EditText et_content;
TextView tv_numOfChar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_content = (EditText)findViewById(R.id.et_content);
tv_numOfChar = (TextView)findViewById(R.id.tv_numOfChar);
et_content.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
Log.i("log","beforeTextChanged:" + s + "------" + start + "------" + after + "------"+ count);
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Log.i("log","onTextChanged:" + s + "------" + start + "------"+ before+ "------" + count);
if (et_content.getText().toString().indexOf(".") >= 0) {
tv_numOfChar.setText("已經輸入\".\"不能重複輸入");
if (et_content.getText().toString().indexOf(".", et_content.getText().toString().indexOf(".") + 1) > 0) {
et_content.setText(et_content.getText().toString().substring(0, et_content.getText().toString().length() - 1));
et_content.setSelection(et_content.getText().toString().length());
}
}
}
@Override
public void afterTextChanged(Editable s) {
Log.i("log","afterTextChanged:" + s);
}
});
}
}