Tries to set the text into composition mode if there is support for it in the framework. - Android android.view.inputmethod

Android examples for android.view.inputmethod:InputConnection

Description

Tries to set the text into composition mode if there is support for it in the framework.

Demo Code

/*/*  w  w w.  j  a  v a2 s . com*/
 * 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.
 */
import android.text.TextUtils;
import android.view.inputmethod.ExtractedText;
import android.view.inputmethod.ExtractedTextRequest;
import android.view.inputmethod.InputConnection;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.regex.Pattern;

public class Main{
    private static boolean sMethodsInitialized;
    private static Method sMethodGetSelectedText;
    private static Method sMethodSetComposingRegion;
    /**
     * Tries to set the text into composition mode if there is support for it in the framework.
     */
    public static void underlineWord(InputConnection ic, SelectedWord word) {
        // Use reflection, for backward compatibility
        // If method not found, there's nothing we can do. It still works but just wont underline
        // the word.
        if (!sMethodsInitialized) {
            initializeMethodsForReflection();
        }
        if (sMethodSetComposingRegion != null) {
            try {
                sMethodSetComposingRegion.invoke(ic, word.start, word.end);
            } catch (InvocationTargetException exc) {
                // Ignore
            } catch (IllegalArgumentException e) {
                // Ignore
            } catch (IllegalAccessException e) {
                // Ignore
            }
        }
    }
    /**
     * Cache method pointers for performance
     */
    private static void initializeMethodsForReflection() {
        try {
            // These will either both exist or not, so no need for separate try/catch blocks.
            // If other methods are added later, use separate try/catch blocks.
            sMethodGetSelectedText = InputConnection.class.getMethod(
                    "getSelectedText", int.class);
            sMethodSetComposingRegion = InputConnection.class.getMethod(
                    "setComposingRegion", int.class, int.class);
        } catch (NoSuchMethodException exc) {
            // Ignore
        }
        sMethodsInitialized = true;
    }
}

Related Tutorials