android – 使用InputConnection.commitText将光标设置在插入文本的开头

InputConnection.commitText(CharSequence text,int newCursorPosition)的文档说newCursorPosition意味着:

int: The new cursor position around the text,in Java characters. If >
0,this is relative to the end of the text – 1; if <= 0,this is
relative to the start of the text.
So a value of 1 will always advance
the cursor to the position after the full text being inserted. Note
that this means you can’t position the cursor within the text,because
the editor can make modifications to the text you are providing so it
is not possible to correctly specify locations there.

this example,如果我输入两个字符,那么将光标定位在它们之间

enter image description here

然后输入另一个字符,如果我将newCursorPosition设置为0或1则无关紧要.光标始终位于插入的末尾.例如打电话

inputConnection.commitText("aaa",0);

要么

inputConnection.commitText("aaa",1);

两者都显示如下光标:

enter image description here

如果我做-1

inputConnection.commitText("aaa",-1);

我明白了

enter image description here

根据文档,预期1和-1结果.为什么不将光标放在插入的开头?我希望0应该是这样的

inputConnection.commitText("aaa",0);

enter image description here

但事实并非如此.为什么不?

最佳答案
这看起来像代码中的缺陷,但你是判断.

在BaseInputConnection中查看replaceText().我相信这是在插入后放置光标的代码. (从commitText()调用replaceText().

在引用的代码中,a是选择开始. b是选择结束.由于示例中没有选择且光标位于索引1,因此a == b == 1.此外,新文本(aaa)未插入(替换选择[a,b]),直到光标位于搬到了新的选择.

Selection.setSelection(content,newCursorPosition)设置光标位置,因此对于0和1在您的示例中产生相同的定位,我希望newCursorPosition的派生值对于两个输入都是相同的.

将光标定位在位置1的两个8之间,让我们通过以下代码进行思考:

if (newCursorPosition > 0) {
    newCursorPosition += b - 1;
} else {
    newCursorPosition += a;
}

输入1,newCursorPosition> 0,所以newCursorPosition = newCursorPosition 1 – 1或1.

对于0的输入,newCursorPosition不是= 0,因此newCursorPosition = newCursorPosition a(0 1)或1.

由于两个输入都产生相同的值,我希望Selection.setSelection(content,newCursorPosition)产生您看到的结果.

我没有完全遵循代码到这个位置,但我相信这是问题所在.我已经在BaseInputConnection中跟踪了具有API 21的Pixel仿真器上的newCursorPosition = 0和newCursorPosition = 1的执行路径,并且上面概述的内容确实成立.

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...