Example usage for android.view.inputmethod InputConnection setComposingText

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

Introduction

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

Prototype

boolean setComposingText(CharSequence text, int newCursorPosition);

Source Link

Document

Replace the currently composing text with the given text, and set the new cursor position.

Usage

From source file:Main.java

/**
 * Append newText to the text field represented by connection.
 * The new text becomes selected.//from   ww  w  .  j  a  va2 s.c o m
 */
public static void appendText(InputConnection connection, String newText) {
    if (connection == null) {
        return;
    }

    // Commit the composing text
    connection.finishComposingText();

    // Add a space if the field already has text.
    CharSequence charBeforeCursor = connection.getTextBeforeCursor(1, 0);
    if (charBeforeCursor != null && !charBeforeCursor.equals(" ") && (charBeforeCursor.length() > 0)) {
        newText = " " + newText;
    }

    connection.setComposingText(newText, 1);
}

From source file:com.anysoftkeyboard.AnySoftKeyboard.java

public void deleteLastCharactersFromInput(int countToDelete) {
    if (countToDelete == 0)
        return;/* w ww . j  a va  2 s.c o m*/

    final int currentLength = mWord.length();
    boolean shouldDeleteUsingCompletion;
    if (currentLength > 0) {
        shouldDeleteUsingCompletion = true;
        if (currentLength > countToDelete) {
            int deletesLeft = countToDelete;
            while (deletesLeft > 0) {
                mWord.deleteLast();
                deletesLeft--;
            }
        } else {
            mWord.reset();
        }
    } else {
        shouldDeleteUsingCompletion = false;
    }
    InputConnection ic = getCurrentInputConnection();
    if (ic != null) {
        if (mPredictionOn && shouldDeleteUsingCompletion) {
            ic.setComposingText(mWord.getTypedWord()/* mComposing */, 1);
        } else {
            ic.deleteSurroundingText(countToDelete, 0);
        }
    }
}

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

private void handleBackWord(InputConnection ic) {
    if (ic == null) {
        return;/*from   w  ww .  j  a  v  a 2s.  co m*/
    }

    if (TextEntryState.isPredicting()) {
        mWord.reset();
        mSuggest.resetNextWordSentence();
        TextEntryState.newSession(mPredictionOn);
        ic.setComposingText("", 1);
        postUpdateSuggestions();
        return;
    }
    // I will not delete more than 128 characters. Just a safe-guard.
    // this will also allow me do just one call to getTextBeforeCursor!
    // Which is always good. This is a part of issue 951.
    CharSequence cs = ic.getTextBeforeCursor(128, 0);
    if (TextUtils.isEmpty(cs)) {
        return;// nothing to delete
    }
    // TWO OPTIONS
    // 1) Either we do like Linux and Windows (and probably ALL desktop
    // OSes):
    // Delete all the characters till a complete word was deleted:
    /*
     * What to do: We delete until we find a separator (the function
     * isBackWordStopChar). Note that we MUST delete a delete a whole word!
     * So if the back-word starts at separators, we'll delete those, and then
     * the word before: "test this,       ," -> "test "
     */
    // Pro: same as desktop
    // Con: when auto-caps is on (the default), this will delete the
    // previous word, which can be annoying..
    // E.g., Writing a sentence, then a period, then ASK will auto-caps,
    // then when the user press backspace (for some reason),
    // the entire previous word deletes.

    // 2) Or we delete all the characters till we encounter a separator, but
    // delete at least one character.
    /*
     * What to do: We delete until we find a separator (the function
     * isBackWordStopChar). Note that we MUST delete a delete at least one
     * character "test this, " -> "test this," -> "test this" -> "test "
     */
    // Pro: Supports auto-caps, and mostly similar to desktop OSes
    // Con: Not all desktop use-cases are here.

    // For now, I go with option 2, but I'm open for discussion.

    // 2b) "test this, " -> "test this"

    final int inputLength = cs.length();
    int idx = inputLength - 1;// it's OK since we checked whether cs is
    // empty after retrieving it.
    while (idx > 0 && !isBackWordStopChar((int) cs.charAt(idx))) {
        idx--;
    }
    ic.deleteSurroundingText(inputLength - idx, 0);// it is always > 0 !
}

From source file:com.anysoftkeyboard.AnySoftKeyboard.java

public void revertLastWord() {
    final int length = mCommittedWord.length() + (mJustAddedAutoSpace ? 1 : 0);
    if (length > 0) {
        mAutoCorrectOn = false;/* w  w  w .  ja va  2 s .  co m*/
        //note: typedWord may be empty
        final InputConnection ic = getCurrentInputConnection();
        mUndoCommitCursorPosition = UNDO_COMMIT_NONE;
        ic.beginBatchEdit();
        ic.deleteSurroundingText(length, 0);
        final CharSequence typedWord = mWord.getTypedWord();
        ic.setComposingText(typedWord/* mComposing */, 1);
        TextEntryState.backspace();
        ic.endBatchEdit();
        performUpdateSuggestions();
        if (mJustAutoAddedWord) {
            removeFromUserDictionary(typedWord.toString());
        }
        getInputView().revertPopTextOutOfKey();
    } else {
        sendDownUpKeyEvents(KeyEvent.KEYCODE_DEL);
    }
}

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();//from   w w  w  .j a va 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 handleBackWord(InputConnection ic) {
    if (ic == null) {
        return;//from www  .  j  av  a2  s .  c o  m
    }

    if (TextEntryState.isPredicting() && mWord.cursorPosition() > 0 && mWord.length() > 0) {
        //sp#ace -> ace
        //cursor == 2
        //length == 5
        //textLeft = word.substring(2, 3) -> word.substring(cursor, length - cursor)
        final CharSequence textLeft = mWord.getTypedWord().subSequence(mWord.cursorPosition(), mWord.length());
        mWord.reset();
        mSuggest.resetNextWordSentence();
        TextEntryState.newSession(mPredictionOn);
        ic.setComposingText(textLeft, 0);
        postUpdateSuggestions();
        return;
    }
    // I will not delete more than 128 characters. Just a safe-guard.
    // this will also allow me do just one call to getTextBeforeCursor!
    // Which is always good. This is a part of issue 951.
    CharSequence cs = ic.getTextBeforeCursor(128, 0);
    if (TextUtils.isEmpty(cs)) {
        return;// nothing to delete
    }
    // TWO OPTIONS
    // 1) Either we do like Linux and Windows (and probably ALL desktop
    // OSes):
    // Delete all the characters till a complete word was deleted:
    /*
     * What to do: We delete until we find a separator (the function
     * isBackWordStopChar). Note that we MUST delete a delete a whole word!
     * So if the back-word starts at separators, we'll delete those, and then
     * the word before: "test this,       ," -> "test "
     */
    // Pro: same as desktop
    // Con: when auto-caps is on (the default), this will delete the
    // previous word, which can be annoying..
    // E.g., Writing a sentence, then a period, then ASK will auto-caps,
    // then when the user press backspace (for some reason),
    // the entire previous word deletes.

    // 2) Or we delete all the characters till we encounter a separator, but
    // delete at least one character.
    /*
     * What to do: We delete until we find a separator (the function
     * isBackWordStopChar). Note that we MUST delete a delete at least one
     * character "test this, " -> "test this," -> "test this" -> "test "
     */
    // Pro: Supports auto-caps, and mostly similar to desktop OSes
    // Con: Not all desktop use-cases are here.

    // For now, I go with option 2, but I'm open for discussion.

    // 2b) "test this, " -> "test this"

    final int inputLength = cs.length();
    int idx = inputLength - 1;// it's OK since we checked whether cs is empty after retrieving it.
    if (isBackWordDeleteChar((int) cs.charAt(idx))) {
        while (idx > 0 && isBackWordDeleteChar((int) cs.charAt(idx - 1))) {
            idx--;
        }
    }
    ic.deleteSurroundingText(inputLength - idx, 0);// it is always > 0 !
}

From source file:com.anysoftkeyboard.AnySoftKeyboard.java

private void handleDeleteLastCharacter(boolean forMultiTap) {
    InputConnection ic = getCurrentInputConnection();

    boolean deleteChar = false;
    if (TextEntryState.isPredicting()) {
        final boolean wordManipulation = mWord.length() > 0 && mWord.cursorPosition() > 0;
        if (wordManipulation) {
            mWord.deleteLast();// w w  w  .ja v  a  2  s  .  c om
            final int cursorPosition;
            if (mWord.cursorPosition() != mWord.length())
                cursorPosition = getCursorPosition(ic);
            else
                cursorPosition = -1;

            if (cursorPosition >= 0)
                ic.beginBatchEdit();

            ic.setComposingText(mWord.getTypedWord(), 1);
            if (mWord.length() == 0) {
                TextEntryState.newSession(mPredictionOn);
            } else if (cursorPosition >= 0) {
                ic.setSelection(cursorPosition - 1, cursorPosition - 1);
            }

            if (cursorPosition >= 0)
                ic.endBatchEdit();

            postUpdateSuggestions();
        } else {
            ic.deleteSurroundingText(1, 0);
        }
    } else {
        deleteChar = true;
    }

    TextEntryState.backspace();
    if (TextEntryState.getState() == TextEntryState.State.UNDO_COMMIT) {
        revertLastWord();
    } else if (deleteChar) {
        //just making sure that
        if (mCandidateView != null)
            mCandidateView.dismissAddToDictionaryHint();

        if (!forMultiTap) {
            sendDownUpKeyEvents(KeyEvent.KEYCODE_DEL);
        } else {
            // this code tries to delete the text in a different way,
            // because of multi-tap stuff
            // using "deleteSurroundingText" will actually get the input
            // updated faster!
            // but will not handle "delete all selected text" feature,
            // hence the "if (!forMultiTap)" above
            final CharSequence beforeText = ic == null ? null : ic.getTextBeforeCursor(1, 0);
            final int textLengthBeforeDelete = (TextUtils.isEmpty(beforeText)) ? 0 : beforeText.length();
            if (textLengthBeforeDelete > 0)
                ic.deleteSurroundingText(1, 0);
            else
                sendDownUpKeyEvents(KeyEvent.KEYCODE_DEL);
        }
    }
}

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();/*from  w ww.  ja v a 2 s.co  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:org.pocketworkstation.pckeyboard.LatinIME.java

private void handleCharacter(int primaryCode, int[] keyCodes) {
    if (mLastSelectionStart == mLastSelectionEnd && TextEntryState.isCorrecting()) {
        abortCorrection(false);//  w  ww.  j  a  v  a 2  s . c  o  m
    }

    if (isAlphabet(primaryCode) && isPredictionOn() && !mModCtrl && !mModAlt && !mModMeta
            && !isCursorTouchingWord()) {
        if (!mPredicting) {
            mPredicting = true;
            mComposing.setLength(0);
            saveWordInHistory(mBestWord);
            mWord.reset();
        }
    }

    if (mModCtrl || mModAlt || mModMeta) {
        commitTyped(getCurrentInputConnection(), true); // sets mPredicting=false
    }

    if (mPredicting) {
        if (isShiftCapsMode() && mKeyboardSwitcher.isAlphabetMode() && mComposing.length() == 0) {
            // Show suggestions with initial caps if starting out shifted,
            // could be either auto-caps or manual shift.
            mWord.setFirstCharCapitalized(true);
        }
        mComposing.append((char) primaryCode);
        mWord.add(primaryCode, keyCodes);
        InputConnection ic = getCurrentInputConnection();
        if (ic != null) {
            // If it's the first letter, make note of auto-caps state
            if (mWord.size() == 1) {
                mWord.setAutoCapitalized(getCursorCapsMode(ic, getCurrentInputEditorInfo()) != 0);
            }
            ic.setComposingText(mComposing, 1);
        }
        postUpdateSuggestions();
    } else {
        sendModifiableKeyChar((char) primaryCode);
    }
    updateShiftKeyState(getCurrentInputEditorInfo());
    TextEntryState.typedCharacter((char) primaryCode, isWordSeparator(primaryCode));
}

From source file:org.distantshoresmedia.keyboard.LatinIME.java

private void handleCharacter(int primaryCode, int[] keyCodes) {
    if (mLastSelectionStart == mLastSelectionEnd && TextEntryState.isCorrecting()) {
        abortCorrection(false);/*from  w ww  . j a va 2 s.c  o  m*/
    }

    if (isAlphabet(primaryCode) && isPredictionOn() && !mModCtrl && !mModAlt && !mModMeta
            && !isCursorTouchingWord()) {
        if (!mPredicting) {
            mPredicting = true;
            mComposing.setLength(0);
            saveWordInHistory(mBestWord);
            mWord.reset();
        }
    }

    if (mModCtrl || mModAlt || mModMeta) {
        commitTyped(getCurrentInputConnection(), true); // sets mPredicting=false
    }

    if (mPredicting) {
        if (isShiftCapsMode() && mKeyboardSwitcher.isAlphabetMode() && mComposing.length() == 0) {
            // Show suggestions with initial caps if starting out shifted,
            // could be either auto-caps or manual shift.
            mWord.setFirstCharCapitalized(true);
        }
        mComposing.append((char) primaryCode);
        mWord.add(primaryCode, keyCodes);
        InputConnection ic = getCurrentInputConnection();
        if (ic != null) {
            // If it's the first letter, make note of auto-caps state
            if (mWord.size() == 1) {
                mWord.setAutoCapitalized(getCursorCapsMode(ic, getCurrentInputEditorInfo()) != 0);
            }
            ic.setComposingText(mComposing, 1);
        }
        postUpdateSuggestions();
    } else {
        sendModifiableKeyChar((char) primaryCode);
    }
    updateShiftKeyState(getCurrentInputEditorInfo());
    if (LatinIME.PERF_DEBUG)
        measureCps();
    TextEntryState.typedCharacter((char) primaryCode, isWordSeparator(primaryCode));
}