使用EditText的addTextChangedListener(new TextWatcher())方法,edittexttextwatcher
(轉:http://www.apkbus.com/android-5257-1-14.html)
在使用EditText的addTextChangedListener(new TextWatcher())方法時(即給EditText增加監聽器):注意: 1、在使用裡面的函數時,不能沒有條件的改變本EditText的內容 , 因為這樣容易引起死迴圈,所以必須要加限制條件////////////////////////////////////////////////////
//給EditText增加監聽器
contentEditText.addTextChangedListener(new TextWatcher() {
int l=0;////////記錄字串被刪除字元之前,字串的長度
int location=0;//記錄游標的位置
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
l=s.length();
location=contentEditText.getSelectionStart();
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
if (l>s.toString().length()) {
gyf.function.face_analysis faceAnalysis=new gyf.function.face_analysis(releaseComment.this);
SpannableStringBuilder sBuilder=faceAnalysis.getSpannableStringBuilder(s.toString());
//eText.setText(sBuilder);
//eText.setText("");
contentEditText.setText(sBuilder);
Editable etable=contentEditText.getText();
Selection.setSelection(etable, location);
//Toast.makeText(releaseComment.this, "11111", Toast.LENGTH_SHORT).show();
}
//Toast.makeText(releaseComment.this, "0000", Toast.LENGTH_SHORT).show();
}
});2、每次重新整理EditText時,游標也會跟著重設,即位置跑到了開頭 如上代碼所示。 有關游標的介紹有:提起Android的EditText的游標選擇問題,可以通過android.text.Selection包提供的方法來實現,Android SDK提供了有關游標選擇的多種方法,比如說getSelectionEnd、getSelectionStart、removeSelection、 selectAll、setSelection,詳細的參數聲明如下
final static int getSelectionEnd(CharSequence text)Return the offset of the selection edge or cursor, or -1 if there is no selection or cursor.final static int getSelectionStart(CharSequence text)Return the offset of the selection anchor or cursor, or -1 if there is no selection or cursor.final static void removeSelection(Spannable text)Remove the selection or cursor, if any, from the text.final static void selectAll(Spannable text)Select the entire text.final static void setSelection(Spannable text, int index)Move the cursor to offset index.static void setSelection(Spannable text, int start, int stop)Set the selection anchor to start and the selection edge to stop.
Android123提示大家,從上面的參數來看,可以發現Spannable類型,常規我們的EditText中的編輯中Editable直接實現Spannable介面,所以我們可以通過下面的方法來設定選擇:
- Editable ea= etEdit.getText(); //etEdit為EditText
- Selection.setSelection(ea, ea.length()-1); // Android開發網提示這裡ea的長度必須大於1。否則會有異常發生