Append new Text to the text field represented by InputConnection. - Android android.view.inputmethod

Android examples for android.view.inputmethod:InputConnection

Description

Append new Text to the text field represented by InputConnection.

Demo Code

/*//from   w w w. j  a v a2s .c  o  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;

public class Main {
    /**
     * Append newText to the text field represented by connection.
     * The new text becomes selected.
     */
    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);
    }
}

Related Tutorials