使用EditText的addTextChangedListener(new TextWatcher())方法


(轉: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。否則會有異常發生


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM