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!
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;
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With