Android: InputConnection is missing a getSelection() method

1k Views Asked by At

Why do I have a setSelection in InputConnection, but not a getSelection()?

Should I just do a getTextBeforeCursor(VERY_HIGH_NUMBER, 0) and calculate the .length() of that string?

3

There are 3 best solutions below

0
On
0
On

I had this problem. I wanted to refactor out references to my EditText and use the InputConnection only. To get the selection start and end, I ended up using getExtractedText(…) method like so:

    private static final ExtractedTextRequest request = new ExtractedTextRequest();
    private InputConnection ic;

// …

    ExtractedText extractedText = ic.getExtractedText(request, 0);
    int start = extractedText.selectionStart;
    int end = extractedText.selectionEnd;
0
On

I agree, it's silly that getSelection() doesn't exist. Your solution works ok but you have to assume that there's just a cursor showing and not a whole selected range of text. I haven't yet figured out how to fill that hole.

EDIT: Oh, of course:

int selStart = ic.getTextBeforeCursor(HIGH_NUMBER, 0).length();
String sel = ic.getSelectedText(); 
int selEnd = selStart + (sel==null? 0: sel.length());