源代码
EditText etContent = findViewById(R.id.etcontent);
etContent.addTextChangedListener(new TextWatcher(){
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2){
}
@Override
public void onTextChanged(CharSequence charsequence, int i, int i1, int i2){
}
@Override
public void afterTextChanged(Editable s){
if(s.length() > MAX_NUM){
s.delete(MAX_NUM, s.length());
Toast.makeText(MainActivity.this, "您的输入已达上限!", Toast.LENGTH_SHORT).show();
}
int num = s.length();
count.setText(String.valueOf(num) + "/10");
}
});
一些无关紧要的介绍(可下翻至调试步骤)
afterTextChangedListener方法来自于TextView.addTextChangedListener
/**
* Adds a TextWatcher to the list of those whose methods are called
* whenever this TextView's text changes.
* 每当此TextView的文本更改时,将TextWatcher添加到其方法被调用的列表中
* <p>
* In 1.0, the {@link TextWatcher#afterTextChanged} method was erroneously
* not called after {@link #setText} calls. Now, doing {@link #setText}
* if there are any text changed listeners forces the buffer type to
* Editable if it would not otherwise be and does call this method.
* 在1.0中,在调用{@link #setText}之后未正确调用{@link TextWatcher#afterTextChanged}方法。
* 现在,如果侦听器中的任何文本已更改,则执行{@link #setText}会强制将缓冲区类型设置为Editable(如果不是),
* 并会调用此方法。
*/
public