public classMainActivityextendsAppCompatActivity {
privateTextViewmTextView;
privateEditTextmEditText;
@Override
public voidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView= (TextView)findViewById(R.id.tv);
mEditText= (EditText)findViewById(R.id.ET);
mEditText.addTextChangedListener(mTextWatcher);
}
TextWatchermTextWatcher=newTextWatcher() {
privateCharSequencetemp;
private inteditStart;
private inteditEnd;
@Override
public voidbeforeTextChanged(CharSequence s,intarg1,intarg2,
intarg3) {
temp= s;
}
@Override
public voidonTextChanged(CharSequence s,intarg1,intarg2,
intarg3) {
mTextView.setText(s);
}
@Override
public voidafterTextChanged(Editable s) {
editStart=mEditText.getSelectionStart();
editEnd=mEditText.getSelectionEnd();
if(temp.length() >10) {
Toast.makeText(MainActivity.this,
"你输入的字数已经超过了限制!", Toast.LENGTH_SHORT)
.show();
s.delete(editStart-1,editEnd);
inttempSelection =editStart;
mEditText.setText(s);
mEditText.setSelection(tempSelection);
}
}
};
}