Android IME,在EditText中设置光标位置 [英] Android IME, set cursor position in EditText
问题描述
我正在使用软键盘,需要在IME编辑文本中设置光标位置.
I am working on soft keyboard where I need to set the cursor position in IME edit text.
如上图所示,我已经创建了软键盘,因为我们可以看到在编辑文本和当前光标位置中输入了一些文本(由蓝色指示器显示).
As shown in above image, I had created soft keyboard, as we can see some text is entered in edit text and current cursor position(shown by blue indicator).
我需要将光标位置设置在当前行的末尾(在我们的示例中,该行的末尾首先由图像中的红色显示)
I need to set the cursor position at the end of the current line (in our case at the end of the line first shown by red color in image)
我尝试使用InputConnection
提供的不同功能,
I have tried with different functions provided with InputConnection
, I tried with,
CharSequence seq = conn.getTextBeforeCursor(1000, 0); // will get as much characters as possible on the left of cursor
还有一件事,我还需要计算编辑文本中的行数(在我们的例子中是两行).
And one more thing, I also need to count to the number of lines in edit text (in our case it's two).
推荐答案
朋友们感谢您的赞赏.两天前我得到了我的 解决方案,但无法更新我的答案.
Hi friends thanks for appreciation. Before two days I got my solution but can't able to update my answer.
为此,我在下面的代码中使用了
For that I used below code,
如果我们使用的API版本大于10,
If we are using api version greater than 10,
sendDownUpKeyEvents(0x0000007b);
因为此方法是在api 11中添加的.
because this method is added in api 11.
如果我们使用的API版本小于11,
If we are using api version less than 11,
if (getCurrentInputConnection() != null) {
CharSequence textAfter = getCurrentInputConnection().getTextAfterCursor(1024, 0);
if (!TextUtils.isEmpty(textAfter)) {
int newPosition = 1;
while (newPosition < textAfter.length()) {
char chatAt = textAfter.charAt(newPosition);
if (chatAt == '\n' || chatAt == '\r') {
break;
}
newPosition++;
}
if (newPosition > textAfter.length())
newPosition = textAfter.length();
try {
CharSequence textBefore = getCurrentInputConnection().getTextBeforeCursor(Integer.MAX_VALUE, 0);
if (!TextUtils.isEmpty(textBefore)) {
newPosition = newPosition + textBefore.length();
}
getCurrentInputConnection().setSelection(newPosition, newPosition);
} catch (Exception e) {
e.printStackTrace();
}
}
}
这篇关于Android IME,在EditText中设置光标位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!