Android 設置EditText光標位置


Android中有很多可編輯的彈出框,其中有些是讓我們來修改其中的字符,這時光標位置定位在哪里呢?
剛剛解了一個bug是關於這個光標的位置的,似乎Android原生中這種情況是把光標定位到字符串的最前面。需求是將光標定位到字符的最后面。
修改的地方是TextView這個控件,因為EditText也是繼承了TextView。在setText方法中有:
  private void setText(CharSequence text, BufferType type,
                          boolean notifyBefore, int oldlen) { 
 …… 
         if (text instanceof Spannable) { 
             Spannable sp = (Spannable) text; 
  
             …… 
             if (mMovement != null) { 
                 mMovement.initialize(this, (Spannable) text);
         //文本是不是Editable的。
         if(this instanceof Editable)
                      //設定光標位置
                      Selection.setSelection((Spannable)text, text.length());
 
                ……
     }

從紅色代碼中可以看出,google是要光標處在缺省文本的末端,但是,log發現 (this instanceof Editable)非真,也就是說Selection.setSelection((Spannable)text, text.length());並不會被執行。

   Log.d("TextView", "(type == BufferType.EDITABLE)="+(type == BufferType.EDITABLE));
     if(type == BufferType.EDITABLE){
          Log.d("TextView","Format text.Set cursor to the end ");
          Selection.setSelection((Spannable)text, text.length());
    }

這個樣修改后即可。

在編寫應用的時候,如果我們要將光標定位到某個位置,可以采用下面的方法:

 CharSequence text = editText.getText();
 //Debug.asserts(text instanceof Spannable);
 if (text instanceof Spannable) {
     Spannable spanText = (Spannable)text;
     Selection.setSelection(spanText, text.length());
 }

其中紅色標記的代碼為你想要設置的位置,此處是設置到文本末尾。


免責聲明!

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



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