(轉:http://www.apkbus.com/android-5257-1-14.html)html
在使用EditText的addTextChangedListener(new TextWatcher())方法時(即給EditText增長監聽器):
注意:
一、在使用裏面的函數時,不能沒有條件的改變本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();
}
});
二、每次刷新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.android
Android123提示你們,從上面的參數來看,能夠發現Spannable類型,常規咱們的EditText中的編輯中Editable直接實現Spannable接口,因此咱們能夠經過下面的方法來設置選擇:
- Editable ea= etEdit.getText(); //etEdit爲EditText
- Selection.setSelection(ea, ea.length()-1); // Android開發網提示這裏ea的長度必須大於1。不然會有異常發生