public class MainActivity extends AppCompatActivity { private TextView mTextView; private EditText mEditText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTextView = (TextView) findViewById(R.id.tv); mEditText = (EditText) findViewById(R.id.et); /** * 监听EditText框中的变化 */ mEditText.addTextChangedListener(new TextWatcher() { private CharSequence temp; private int editStart; private int editEnd; /** * 文本变化之前 * @param s * @param start * @param count * @param after */ @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { temp = s; } /** * 文本变化中 * @param s * @param start * @param before * @param count */ @Override public void onTextChanged(CharSequence s, int start, int before, int count) { mTextView.setText("输入的结果为:"+s); } /** * 文本变化之后 * @param s */ @Override public void afterTextChanged(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); int tempSelection = editStart; mEditText.setText(s); mEditText.setSelection(tempSelection); } } }); } }
结果:
![](https://i-blog.csdnimg.cn/blog_migrate/256e7a8a8376ac5e548b4b3fa0a0ba5d.jpeg)