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

Android examples for android.view.inputmethod:InputConnection

Description

get Previous Word from InputConnection

Demo Code

/*/*from   w w  w . j ava 2  s  . co m*/
 * Copyright (C) 2009 Google Inc.
 * 
 * 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.
 */
//package com.java2s;

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
     */
    private static final int LOOKBACK_CHARACTER_NUM = 15;
    private static final Pattern spaceRegex = Pattern.compile("\\s+");

    public static CharSequence getPreviousWord(InputConnection connection,
            String sentenceSeperators) {
        //TODO: Should fix this. This could be slow!
        CharSequence prev = connection.getTextBeforeCursor(
                LOOKBACK_CHARACTER_NUM, 0);
        if (prev == null) {
            return null;
        }
        String[] w = spaceRegex.split(prev);
        if (w.length >= 2 && w[w.length - 2].length() > 0) {
            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];
        } else {
            return null;
        }
    }
}

Related Tutorials