How to automatically insert text at the cursor position of EditText

When returning non-user input data from the interface or other activities, you want to insert after the cursor position in the EditText input box, such as inserting a picture, a sentence. The following piece of code achieves what we want:

/**
 * 实现将扫描结果插入在EditText光标处
 * @param editText 
 * @param index 获取光标所在位置
 * @param text 插入的文本
 */
private void insertAtFocusedPosition(EditText editText,String text){
    int index = editText.getSelectionStart();//获取光标所在位置
    Editable edit = editText.getEditableText();//获取EditText的文字
    if (index < 0 || index >= edit.length() ){
        edit.append(text);
    }else{
        edit.insert(index,text);//光标所在位置插入文字
    }
}
Published 381 original articles · praised 85 · 80,000 views +

Guess you like

Origin blog.csdn.net/weixin_40763897/article/details/105384972