android 設置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 }

其中紅色標記的代碼爲你想要設置的位置,此處是設置到文本末尾。
發佈了21 篇原創文章 · 獲贊 1 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章