Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selection using Android IME

In my input method service I am trying to select the text before the current cursor position. Following is the code snippet

InputConnection inputConnection = getCurrentInputConnection();
ExtractedText extractedText = inputConnection.getExtractedText(new ExtractedTextRequest(), 0);
inputConnection.setSelection(extractedText.selectionStart-1,extractedText.selectionEnd);

InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.updateSelection(null, extractedText.selectionStart-1,extractedText.selectionEnd, 0, 0);

This has a very flaky behaviour, sometimes it selects, sometimes it just moves the cursor one step back.

Can anybody point out what is it that I am doing wrong?

ADDITION:

Since this question has remained unanswered for some time, I would like to pose an alternate question. I was looking around for some alternate ways of selecting text and on the hackers-Keyboard, pressing the shift and then a arrow key does the trick, but I am not able to replicate the process. I tried sending the d-pad keys down and up key-events along with meta_shift_on flag.

But that is not working... Again, what am I doing wrong?

like image 899
flide Avatar asked Aug 13 '26 07:08

flide


1 Answers

Best solution for selection in IME

private void SelectionLeft() {
        ExtractedText extractedText = mLatinIme.getCurrentInputConnection().getExtractedText(new ExtractedTextRequest(), 0);
        if (extractedText == null || extractedText.text == null) return;

        int selectionStart = extractedText.selectionStart;
        int selectionEnd = extractedText.selectionEnd;


        mLatinIme.getCurrentInputConnection().setSelection(selectionStart, selectionEnd - 1);

    }

    private void SelectionRight() {
        ExtractedText extractedText = mLatinIme.getCurrentInputConnection().getExtractedText(new ExtractedTextRequest(), 0);
        if (extractedText == null || extractedText.text == null) return;

        int selectionStart = extractedText.selectionStart;
        int selectionEnd = extractedText.selectionEnd;

        mLatinIme.getCurrentInputConnection().setSelection(selectionStart, selectionEnd + 1);

    }
like image 154
S.J Hashmi Avatar answered Aug 15 '26 21:08

S.J Hashmi