Android TextWatcher監控EditText,TextView
阿新 • • 發佈:2019-01-23
package com.android.text;
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
publicclass TextWatcherDemo extends Activity {
private TextView mTextView;
private EditText mEditText;
/** Called when the activity is first created. */
@Override
publicvoid onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTextView = (TextView)findViewById(R.id.tv);
mEditText = (EditText)findViewById(R.id.ET);
mEditText.addTextChangedListener(mTextWatcher);
}
TextWatcher mTextWatcher =new TextWatcher() {
private CharSequence temp;
privateint editStart ;
privateint editEnd ;
@Override
publicvoid beforeTextChanged(CharSequence s, int arg1, int arg2,
int arg3) {
temp = s;
}
@Override
publicvoid onTextChanged(CharSequence s, int arg1, int arg2,
int arg3) {
mTextView.setText(s);
}
@Override
publicvoid afterTextChanged(Editable s) {
editStart = mEditText.getSelectionStart();
editEnd = mEditText.getSelectionEnd();
if (temp.length() >10) {
Toast.makeText(TextWatcherDemo.this,
"你輸入的字數已經超過了限制!", Toast.LENGTH_SHORT)
.show();
s.delete(editStart-1, editEnd);
int tempSelection = editStart;
mEditText.setText(s);
mEditText.setSelection(tempSelection);
}
}
};
}