8

I am working on an Android soft keyboard and was wondering, is there a way for the keyboard to get the current cursor position? I am currently using the following code:

connection.getTextBeforeCursor(Integer.MAX_VALUE, 0).length()

However, this is very slow (even for a small amount of text, it can take up to 50ms -- running on a Galaxy Nexus, so this would likely be even slower for lower end phones). I have also tested it on a Droid Incredible, and the lag is even more severe.

In the function onUpdateSelection, you are given the new cursor position. However, this function is not always called and therefore storing the value provided by it for future use is not reliable.

Since you can set the cursor position and get selected text (but not the position of the selected text), shouldn't there be a function to get the cursor position?

Thanks for the help!

General Grievance
  • 4,555
  • 31
  • 31
  • 45
lrAndroid
  • 2,834
  • 18
  • 27

2 Answers2

9

This is an older question, but I ran into the same problem recently. To get the cursor position:

InputConnection ic = getCurrentInputConnection();
ExtractedText et = ic.getExtractedText(new ExtractedTextRequest(), 0);
int selectionStart = et.selectionStart;
int selectionEnd = et.selectionEnd;
David Albers
  • 253
  • 4
  • 10
  • This looks like it is working on selected text. The questions seems to be about just a normal cursor in text without a selection. Does this code work in this case? – Burhan Ali Aug 14 '13 at 17:54
  • 3
    Yes, in that case, selectionStart and selectionEnd with be equal. – David Albers Aug 14 '13 at 21:02
1

I'm a few years late to the party here, but it doesn't look like this question was ever answered within the context provided. The question states that the following line of code takes up to 50 ms to run:

 connection.getTextBeforeCursor(Integer.MAX_VALUE, 0).length()

This is likely because the Android implementation of the getTextBeforeCursor(int, int) method appears to be attempting to instantiate a CharSequence array of length n prior to searching for the characters requested. In this case it is attempting to instantiate an array of length Integer.MAX_VALUE. The actual array returned is trimmed to the appropriate size.

I've been using a similar method to obtain the cursor position from the InputConnection, but have limited the value of n to a maximum value that I control. So, if I set the maximum characters for an EditText to 25 characters, then that will be my n value. And, it's pretty fast. Here's an example of my approach:

int cursorPosition = mInputConnection.getTextBeforeCursor(MAX_CHARACTERS, 0).length();
Don Brody
  • 1,689
  • 2
  • 18
  • 30