(轉:http://www.apkbus.com/android-5257-1-14.html)
//給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();
}
});
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。否則會有異常發生