Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import android.text.Editable;

import android.widget.EditText;

public class Main {
    /**
     * Substitute the selection of given {@link EditText} with specified text.<br />
     * If no text is selected then specified text will be inserted at current cursor position.<br />
     * Newly inserted text will be selected.
     * @param editText Target {@link EditText}.
     * @param txt Text to insert.
     * @param select {@code true} to select newly added text.
     */
    public static void setTextInsideSelection(EditText editText, String txt, boolean select) {
        Editable editable;
        int selStart;
        int selEnd;

        editable = editText.getText();

        selStart = editText.getSelectionStart();
        selEnd = editText.getSelectionEnd();
        if (selStart > selEnd) {
            int tmp = selStart;
            selStart = selEnd;
            selEnd = tmp;
        }

        editable.replace(selStart, selEnd, txt);

        if (select) {
            editText.setSelection(selStart, selStart + txt.length());
        } else {
            editText.setSelection(selStart + txt.length());
        }
    }
}