TextWatcher提供了3个回调方法:
1.文本改变前:beforeTextChanged <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical"> <TextView android:id="@+id/tv" android:layout_width="fill_parent" android:layout_height="wrap_content" android:ellipsize="marquee" android:focusable="true" android:focusableInTouchMode="true" android:marqueeRepeatLimit="marquee_forever" android:scrollHorizontally="true" android:text="输入的结果为:" /> <EditText android:id="@+id/et" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="请输入:"/> </LinearLayout> 主类: 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); } } }); } } 结果: |