Android 设置EditText光标位置
2024-10-18 22:39:14
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());
}
其中红色标记的代码为你想要设置的位置,此处是设置到文本末尾。
最新文章
- Golang 语法学习笔记
- JS表单验证
- ng-style 的坑 - 对性能的影响
- 日期对象-Date
- jQuery技术交流资料
- 翻译:《What can I hold you with?》—— 博尔赫斯《英文诗两首》之一。
- spoj 7258 Lexicographical Substring Search (后缀自动机)
- ionic入门之色彩、图标和边距和界面组件:列表
- -协同IResult
- poj2349,最小生成树!
- python_冒泡算法
- leetcode算法:Reshape the Matrix
- Linux命令学习: grep命令
- 51nod--1185 威佐夫游戏 V2 (博弈, 乘法模拟)
- 【spring】-- 手写一个最简单的IOC框架
- JAVA web 使用有盟推送总结
- 理解Spark的核心RDD
- 【系统移植】uboot详细分析
- kohana导入和导出
- 插件使用-HighChart
热门文章
- (poj 3177) Redundant Paths
- 函数 resize和reserve的区别
- [java学习笔记]java语言基础概述之运算符&;程序流程控制&;for循环嵌套
- Apple MDM Supported configurable settings
- DTcms手机版使用余额支付 提示信息跳转到PC版的错误。以及提交订单不打开新页面
- xshell连接linux服务器切换至oracle的sqlplus控制台时,无法使用回车键的解决方案!
- Python在Windows下开发环境配置汇总
- 1 server - n clients 模型实现(select)
- Session_set_save_handler 之 文本模式实现
- oracle 将科学计数法数据转换为非科学计数法数据