EditText在光標處插入字符
阿新 • • 發佈:2018-06-02
AD lec ins 快捷 ets 快捷鍵 case ase ret
寫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;
EditText在光標處插入字符