Java tutorial
//package com.java2s; /* * 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.view.inputmethod.InputConnection; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class Main { private static boolean sMethodsInitialized; private static Method sMethodGetSelectedText; private static Method sMethodSetComposingRegion; /** * Returns the selected text between the selStart and selEnd positions. */ 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; } /** * 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; } }