get Previous Word from Cursor - Android android.view.inputmethod

Android examples for android.view.inputmethod:InputConnection

Description

get Previous Word from Cursor

Demo Code

/*/* w  ww .j  ava 2 s.  c  om*/
 * Copyright (C) 2009 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
import android.view.inputmethod.ExtractedText;
import android.view.inputmethod.ExtractedTextRequest;
import android.view.inputmethod.InputConnection;
import java.util.regex.Pattern;

public class Main{
    /**
     * Number of characters we want to look back in order to identify the previous word
     */
    // Provision for a long word pair and a separator
    private static final int LOOKBACK_CHARACTER_NUM = BinaryDictionary.MAX_WORD_LENGTH * 2 + 1;
    private static final Pattern spaceRegex = Pattern.compile("\\s+");
    public static CharSequence getPreviousWord(InputConnection connection,
            String sentenceSeperators) {
        //TODO: Should fix this. This could be slow!
        if (null == connection)
            return null;
        CharSequence prev = connection.getTextBeforeCursor(
                LOOKBACK_CHARACTER_NUM, 0);
        return getPreviousWord(prev, sentenceSeperators);
    }
    public static CharSequence getPreviousWord(CharSequence prev,
            String sentenceSeperators) {
        if (prev == null)
            return null;
        String[] w = spaceRegex.split(prev);

        // If we can't find two words, or we found an empty word, return null.
        if (w.length < 2 || w[w.length - 2].length() <= 0)
            return null;

        // If ends in a separator, return null
        char lastChar = w[w.length - 2]
                .charAt(w[w.length - 2].length() - 1);
        if (sentenceSeperators.contains(String.valueOf(lastChar)))
            return null;

        return w[w.length - 2];
    }
}

Related Tutorials