设置EditText光标位置

来源:互联网 发布:淘宝摄影视频接单平台 编辑:程序博客网 时间:2024/05/22 01:40

转自:http://www.cnblogs.com/nanhuchongzi/archive/2012/04/17/2444451.html

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 }

其中红色标记的代码为你想要设置的位置,此处是设置到文本末尾。

0 0