Example usage for android.view.inputmethod InputConnection setSelection

List of usage examples for android.view.inputmethod InputConnection setSelection

Introduction

In this page you can find the example usage for android.view.inputmethod InputConnection setSelection.

Prototype

boolean setSelection(int start, int end);

Source Link

Document

Set the selection of the text editor.

Usage

From source file:Main.java

/**
 * Returns the selected text between the selStart and selEnd positions.
 *///  w  w w . ja v  a  2  s .co m
private static CharSequence getSelectedText(InputConnection ic, int selStart, int selEnd) {
    // Use reflection, for backward compatibility
    CharSequence result = null;
    if (!sMethodsInitialized) {
        initializeMethodsForReflection();
    }
    if (sMethodGetSelectedText != null) {
        try {
            result = (CharSequence) sMethodGetSelectedText.invoke(ic, 0);
            return result;
        } catch (InvocationTargetException exc) {
            // Ignore
        } catch (IllegalArgumentException e) {
            // Ignore
        } catch (IllegalAccessException e) {
            // Ignore
        }
    }
    // Reflection didn't work, try it the poor way, by moving the cursor to the start,
    // getting the text after the cursor and moving the text back to selected mode.
    // TODO: Verify that this works properly in conjunction with 
    // LatinIME#onUpdateSelection
    ic.setSelection(selStart, selEnd);
    result = ic.getTextAfterCursor(selEnd - selStart, 0);
    ic.setSelection(selStart, selEnd);
    return result;
}

From source file:com.volosyukivan.WiFiInputMethod.java

private void selectAll(InputConnection conn) {
    ExtractedText text = conn.getExtractedText(req, 0);
    try {/*ww w  . j  a va2  s.co m*/
        conn.setSelection(0, text.text.length());
    } catch (NullPointerException e) {
        // Potentially, text or text.text can be null
    }
}

From source file:com.googlecode.eyesfree.brailleback.BrailleIME.java

private boolean setCursor(InputConnection ic, int pos) {
    if (mCurrentText == null) {
        return false;
    }//  ww w  . j  ava 2s.c  o m
    int textLen = mCurrentText.length();
    pos = (pos < 0) ? 0 : ((pos <= textLen) ? pos : textLen);
    return ic.setSelection(pos, pos);
}

From source file:com.volosyukivan.WiFiInputMethod.java

private void keyHome(InputConnection conn) {
    boolean control = pressedKeys.contains(KEY_CONTROL);
    boolean shift = pressedKeys.contains(KeyEvent.KEYCODE_SHIFT_LEFT);
    ExtractedText text = conn.getExtractedText(req, 0);
    if (text == null)
        return;/*from   ww  w.j a  v  a 2s . co  m*/

    int end;
    if (control) {
        end = 0;
    } else {
        end = text.text.toString().lastIndexOf('\n', text.selectionEnd - 1);
        end++;
    }
    int start = shift ? text.selectionStart : end;
    Log.d("wifikeyboard", "start = " + start + " end = " + end);
    conn.setSelection(start, end);
}

From source file:com.volosyukivan.WiFiInputMethod.java

private void keyEnd(InputConnection conn) {
    boolean control = pressedKeys.contains(KEY_CONTROL);
    boolean shift = pressedKeys.contains(KeyEvent.KEYCODE_SHIFT_LEFT);
    ExtractedText text = conn.getExtractedText(req, 0);
    if (text == null)
        return;//  ww w  .  ja  v  a  2  s .c om
    int end;
    if (control) {
        end = text.text.length();
    } else {
        end = text.text.toString().indexOf('\n', text.selectionEnd);
        if (end == -1)
            end = text.text.length();
    }
    int start = shift ? text.selectionStart : end;
    Log.d("wifikeyboard", "start = " + start + " end = " + end);
    conn.setSelection(start, end);
}

From source file:com.volosyukivan.WiFiInputMethod.java

private void wordLeft(InputConnection conn) {
    boolean shift = pressedKeys.contains(KeyEvent.KEYCODE_SHIFT_LEFT);
    ExtractedText text = conn.getExtractedText(req, 0);
    if (text == null)
        return;// w  w w. j  a  va  2s.com

    int end = text.selectionEnd - 1;

    String str = text.text.toString();

    for (; end >= 0; end--) {
        if (!Character.isSpace(str.charAt(end)))
            break;
    }
    for (; end >= 0; end--) {
        if (Character.isSpace(str.charAt(end)))
            break;
    }
    end++;
    int start = shift ? text.selectionStart : end;
    Log.d("wifikeyboard", "start = " + start + " end = " + end);
    conn.setSelection(start, end);
}

From source file:com.volosyukivan.WiFiInputMethod.java

private void wordRight(InputConnection conn) {
    boolean shift = pressedKeys.contains(KeyEvent.KEYCODE_SHIFT_LEFT);
    ExtractedText text = conn.getExtractedText(req, 0);
    if (text == null)
        return;/*  ww w .  j a v  a  2 s  .c om*/

    int end = text.selectionEnd;
    String str = text.text.toString();
    int len = str.length();

    for (; end < len; end++) {
        if (!Character.isSpace(str.charAt(end)))
            break;
    }
    for (; end < len; end++) {
        if (Character.isSpace(str.charAt(end)))
            break;
    }
    int start = shift ? text.selectionStart : end;
    Log.d("wifikeyboard", "start = " + start + " end = " + end);
    conn.setSelection(start, end);
}

From source file:org.kde.kdeconnect.Plugins.RemoteKeyboardPlugin.RemoteKeyboardPlugin.java

private boolean handleSpecialKey(int key, boolean shift, boolean ctrl, boolean alt) {
    int keyEvent = specialKeyMap.get(key, 0);
    if (keyEvent == 0)
        return false;
    InputConnection inputConn = RemoteKeyboardService.instance.getCurrentInputConnection();
    //        Log.d("RemoteKeyboardPlugin", "Handling special key " + key + " translated to " + keyEvent + " shift=" + shift + " ctrl=" + ctrl + " alt=" + alt);

    // special sequences:
    if (ctrl && (keyEvent == KeyEvent.KEYCODE_DPAD_RIGHT)) {
        // Ctrl + right -> next word
        ExtractedText extractedText = inputConn.getExtractedText(new ExtractedTextRequest(), 0);
        int pos = getCharPos(extractedText, ' ', keyEvent == KeyEvent.KEYCODE_DPAD_RIGHT);
        if (pos == -1)
            pos = currentTextLength(extractedText);
        else/*ww  w . j  av a  2  s. com*/
            pos++;
        int startPos = pos;
        int endPos = pos;
        if (shift) { // Shift -> select word (otherwise jump)
            Pair<Integer, Integer> sel = currentSelection(extractedText);
            int cursor = currentCursorPos(extractedText);
            //                Log.d("RemoteKeyboardPlugin", "Selection (to right): " + sel.first + " / " + sel.second + " cursor: " + cursor);
            startPos = cursor;
            if (sel.first < cursor || // active selection from left to right -> grow
                    sel.first > sel.second) // active selection from right to left -> shrink
                startPos = sel.first;
        }
        inputConn.setSelection(startPos, endPos);
    } else if (ctrl && keyEvent == KeyEvent.KEYCODE_DPAD_LEFT) {
        // Ctrl + left -> previous word
        ExtractedText extractedText = inputConn.getExtractedText(new ExtractedTextRequest(), 0);
        int pos = getCharPos(extractedText, ' ', keyEvent == KeyEvent.KEYCODE_DPAD_RIGHT);
        if (pos == -1)
            pos = 0;
        else
            pos++;
        int startPos = pos;
        int endPos = pos;
        if (shift) {
            Pair<Integer, Integer> sel = currentSelection(extractedText);
            int cursor = currentCursorPos(extractedText);
            //                Log.d("RemoteKeyboardPlugin", "Selection (to left): " + sel.first + " / " + sel.second + " cursor: " + cursor);
            startPos = cursor;
            if (cursor < sel.first || // active selection from right to left -> grow
                    sel.first < sel.second) // active selection from right to left -> shrink
                startPos = sel.first;
        }
        inputConn.setSelection(startPos, endPos);
    } else if (shift && (keyEvent == KeyEvent.KEYCODE_DPAD_LEFT || keyEvent == KeyEvent.KEYCODE_DPAD_RIGHT
            || keyEvent == KeyEvent.KEYCODE_DPAD_UP || keyEvent == KeyEvent.KEYCODE_DPAD_DOWN
            || keyEvent == KeyEvent.KEYCODE_MOVE_HOME || keyEvent == KeyEvent.KEYCODE_MOVE_END)) {
        // Shift + up/down/left/right/home/end
        long now = SystemClock.uptimeMillis();
        inputConn.sendKeyEvent(new KeyEvent(now, now, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_SHIFT_LEFT, 0, 0));
        inputConn.sendKeyEvent(
                new KeyEvent(now, now, KeyEvent.ACTION_DOWN, keyEvent, 0, KeyEvent.META_SHIFT_LEFT_ON));
        inputConn.sendKeyEvent(
                new KeyEvent(now, now, KeyEvent.ACTION_UP, keyEvent, 0, KeyEvent.META_SHIFT_LEFT_ON));
        inputConn.sendKeyEvent(new KeyEvent(now, now, KeyEvent.ACTION_UP, KeyEvent.KEYCODE_SHIFT_LEFT, 0, 0));
    } else if (keyEvent == KeyEvent.KEYCODE_NUMPAD_ENTER || keyEvent == KeyEvent.KEYCODE_ENTER) {
        // Enter key
        EditorInfo editorInfo = RemoteKeyboardService.instance.getCurrentInputEditorInfo();
        //            Log.d("RemoteKeyboardPlugin", "Enter: " + editorInfo.imeOptions);
        if (editorInfo != null
                && (((editorInfo.imeOptions & EditorInfo.IME_FLAG_NO_ENTER_ACTION) == 0) || ctrl)) { // Ctrl+Return overrides IME_FLAG_NO_ENTER_ACTION (FIXME: make configurable?)
            // check for special DONE/GO/etc actions first:
            int[] actions = { EditorInfo.IME_ACTION_GO, EditorInfo.IME_ACTION_NEXT, EditorInfo.IME_ACTION_SEND,
                    EditorInfo.IME_ACTION_SEARCH, EditorInfo.IME_ACTION_DONE }; // note: DONE should be last or we might hide the ime instead of "go"
            for (int i = 0; i < actions.length; i++) {
                if ((editorInfo.imeOptions & actions[i]) == actions[i]) {
                    //                        Log.d("RemoteKeyboardPlugin", "Enter-action: " + actions[i]);
                    inputConn.performEditorAction(actions[i]);
                    return true;
                }
            }
        } else {
            // else: fall back to regular Enter-event:
            //                Log.d("RemoteKeyboardPlugin", "Enter: normal keypress");
            inputConn.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, keyEvent));
            inputConn.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, keyEvent));
        }
    } else {
        // default handling:
        inputConn.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, keyEvent));
        inputConn.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, keyEvent));
    }

    return true;
}

From source file:com.yek.keyboard.anysoftkeyboard.AnySoftKeyboard.java

private void handleCharacter(final int primaryCode, final Keyboard.Key key, final int multiTapIndex,
        int[] nearByKeyCodes) {
    if (BuildConfig.DEBUG)
        Logger.d(TAG, "handleCharacter: %d, isPredictionOn: %s, mPredicting: %s", primaryCode, isPredictionOn(),
                TextEntryState.isPredicting());

    mExpectingSelectionUpdateBy = SystemClock.uptimeMillis() + MAX_TIME_TO_EXPECT_SELECTION_UPDATE;
    if (TextEntryState.isReadyToPredict() && isAlphabet(primaryCode) && !isCursorTouchingWord()) {
        TextEntryState.newSession(mPredictionOn);
        mUndoCommitCursorPosition = UNDO_COMMIT_NONE;
        mWord.reset();/* ww  w. j  a v a  2 s  .  c  o m*/
        mAutoCorrectOn = mAutoComplete;
        TextEntryState.typedCharacter((char) primaryCode, false);
        if (mShiftKeyState.isActive()) {
            mWord.setFirstCharCapitalized(true);
        }
    } else if (TextEntryState.isPredicting()) {
        TextEntryState.typedCharacter((char) primaryCode, false);
    }

    mLastCharacterWasShifted = (getInputView() != null) && getInputView().isShifted();

    if (TextEntryState.isPredicting()) {
        final InputConnection ic = getCurrentInputConnection();
        mWord.add(primaryCode, nearByKeyCodes);
        ChewbaccaOnTheDrums.onKeyTyped(mWord, getApplicationContext());

        if (ic != null) {
            final int cursorPosition;
            if (mWord.cursorPosition() != mWord.length()) {
                //Cursor is not at the end of the word. I'll need to reposition
                cursorPosition = mGlobalCursorPosition + 1/*adding the new character*/;
                ic.beginBatchEdit();
            } else {
                cursorPosition = -1;
            }

            ic.setComposingText(mWord.getTypedWord(), 1);
            if (cursorPosition > 0) {
                ic.setSelection(cursorPosition, cursorPosition);
                ic.endBatchEdit();
            }
        }
        // this should be done ONLY if the key is a letter, and not a inner
        // character (like ').
        if (isSuggestionAffectingCharacter(primaryCode)) {
            postUpdateSuggestions();
        } else {
            // just replace the typed word in the candidates view
            if (mCandidateView != null)
                mCandidateView.replaceTypedWord(mWord.getTypedWord());
        }
    } else {
        sendKeyChar((char) primaryCode);
    }
    mJustAutoAddedWord = false;
}

From source file:com.anysoftkeyboard.AnySoftKeyboard.java

private void handleCharacter(final int primaryCode, final Key key, final int multiTapIndex,
        int[] nearByKeyCodes) {
    if (BuildConfig.DEBUG)
        Logger.d(TAG, "handleCharacter: %d, isPredictionOn: %s, mPredicting: %s", primaryCode, isPredictionOn(),
                TextEntryState.isPredicting());

    mExpectingSelectionUpdateBy = SystemClock.uptimeMillis() + MAX_TIME_TO_EXPECT_SELECTION_UPDATE;
    if (TextEntryState.isReadyToPredict() && isAlphabet(primaryCode) && !isCursorTouchingWord()) {
        TextEntryState.newSession(mPredictionOn);
        mUndoCommitCursorPosition = UNDO_COMMIT_NONE;
        mWord.reset();/* ww  w  .j  a v  a 2  s . c  om*/
        mAutoCorrectOn = mAutoComplete;
        TextEntryState.typedCharacter((char) primaryCode, false);
        if (mShiftKeyState.isActive()) {
            mWord.setFirstCharCapitalized(true);
        }
    } else if (TextEntryState.isPredicting()) {
        TextEntryState.typedCharacter((char) primaryCode, false);
    }

    mLastCharacterWasShifted = (getInputView() != null) && getInputView().isShifted();

    if (TextEntryState.isPredicting()) {
        final InputConnection ic = getCurrentInputConnection();
        mWord.add(primaryCode, nearByKeyCodes);
        ChewbaccaOnTheDrums.onKeyTyped(mWord, getApplicationContext());

        if (ic != null) {
            final int cursorPosition;
            if (mWord.cursorPosition() != mWord.length()) {
                //Cursor is not at the end of the word. I'll need to reposition
                cursorPosition = mGlobalCursorPosition + 1/*adding the new character*/;
                ic.beginBatchEdit();
            } else {
                cursorPosition = -1;
            }

            ic.setComposingText(mWord.getTypedWord(), 1);
            if (cursorPosition > 0) {
                ic.setSelection(cursorPosition, cursorPosition);
                ic.endBatchEdit();
            }
        }
        // this should be done ONLY if the key is a letter, and not a inner
        // character (like ').
        if (isSuggestionAffectingCharacter(primaryCode)) {
            postUpdateSuggestions();
        } else {
            // just replace the typed word in the candidates view
            if (mCandidateView != null)
                mCandidateView.replaceTypedWord(mWord.getTypedWord());
        }
    } else {
        sendKeyChar((char) primaryCode);
    }
    mJustAutoAddedWord = false;
}