android中edittext监听文字变化,使用TextWatcher监听EditText变化
TextWatcher提供了3個回調方法:
1.文本改變前:beforeTextChanged
2.文本改變:onTextChanged
3.文本改變之后:afterTextChanged
布局文件:
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
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="輸入的結果為:" />
android:id="@+id/et"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="請輸入:"/>
主類:
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);
}
}
});
}
}
結果:
(責任編輯:最模板)
總結
以上是生活随笔為你收集整理的android中edittext监听文字变化,使用TextWatcher监听EditText变化的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [css] 固定的外框尺寸,里面的图片
- 下一篇: [css] 你了解css3的curre