EditText在光标处插入字符

写MarkDown编译器的快捷键时碰到的常见但又不太好想的问题

通用代码

//获取光标位置
    private int getEditTextCursorIndex(EditText editText){
        return editText.getSelectionStart();
    }
    //向光标处插入文本
    private void insertText(EditText editText,String string){
        editText.getText().insert(getEditTextCursorIndex(editText),string);
    }
    //光标左移
    private void setEditTextCusorRollLeft(EditText editText,int rollLeft){
        editText.setSelection(getEditTextCursorIndex(editText)-rollLeft);
    }

快捷键实现样例

case R.id.sk_head1:
                insertText(mEdContent,"# ");
                break;
            case R.id.sk_head2:
                insertText(mEdContent,"## ");
                break;
            case R.id.sk_head3:
                insertText(mEdContent,"### ");
                break;
            case R.id.sk_code:
                insertText(mEdContent,"```\n\n```");
                setEditTextCusorRollLeft(mEdContent,4);
                break;
            case R.id.sk_use:
                mEdContent.append("> ");
                break;
            case R.id.sk_xieti:
                mEdContent.append("**");
                setEditTextCusorRollLeft(mEdContent,1);
                break;
posted @ 2018-06-02 13:24  秦川德利齐  阅读(747)  评论(0编辑  收藏  举报