zoukankan      html  css  js  c++  java
  • 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());
     }

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

  • 相关阅读:
    Generate Parentheses (Java)
    leetcode15
    MD5
    leetcode409
    Vue第一个简单的例子
    SpringBoot和Ajax通信
    如何使用安装光盘为本机创建yum repository
    Less known Solaris features: svccfg editprop (ZT)
    Rename Oracle Managed File (OMF) datafiles in ASM(ZT)
    跨数据文件删除flashback database
  • 原文地址:https://www.cnblogs.com/zhujiabin/p/4270232.html
Copyright © 2011-2022 走看看