設置EditText光標位置


轉載請注明出處。

Android中有很多可編輯的彈出框,其中有些是讓我們來修改其中的字符,這時光標位置定位在哪里呢?

剛剛解了一個bug是關於這個光標的位置的,似乎Android原生中這種情況是把光標定位到字符串的最前面。需求是將光標定位到字符的最后面。

修改的地方是TextView這個控件,因為EditText也是繼承了TextView。在setText方法中有:

 1  private void setText(CharSequence text, BufferType type,
 2                          boolean notifyBefore, int oldlen) {
 3 ……
 4         if (text instanceof Spannable) {
 5             Spannable sp = (Spannable) text;
 6 
 7             ……
 8             if (mMovement != null) {
 9                 mMovement.initialize(this, (Spannable) text);
10         //文本是不是Editable的。
11         if(this instanceof Editable)
12                      //設定光標位置
13                      Selection.setSelection((Spannable)text, text.length());
14 
15                ……
16     }

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

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

這個樣修改后即可。

 

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

1 CharSequence text = editText.getText();
2 //Debug.asserts(text instanceof Spannable);
3 if (text instanceof Spannable) {
4     Spannable spanText = (Spannable)text;
5     Selection.setSelection(spanText, text.length());
6 }

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

 


免責聲明!

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



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