- 获取光标位置
int index = editText.getSelectionStart();
- 在光标处插入字符
int index = editText.getSelectionStart();
Editable editable = editText.getText();
editable.insert(index, "aaaa");
- 删除光标前字符
int index = editText.getSelectionStart();
Editable editable = editText.getText();
editable.delete(index-1, index);
- 选中文字
//选中所有字符
mEditText.setSelection(0, str.length());
- 点击EditText获取焦点显示光标且不弹出软键盘
editText.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
editText.requestFocus();
int inType = editText.getInputType();
editText.setInputType(InputType.TYPE_NULL);
editText.onTouchEvent(event);
editText.setInputType(inType);
editText.setSelection(editText.getText().length());
return true;
}
});
- 处理软键盘回删按钮backSpace时不会回调OnKeyListener
自定义一个View继承自EditText,重写其onCreateInputConnection(EditInfo)方法:
public class DeletableEditText extends EditText {
public DeletableEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public DeletableEditText(Context context, AttributeSet attrs) {
super(context, attrs);
}
public DeletableEditText(Context context) {
super(context);
}
@Override
public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
return new DeleteInputConnection(super.onCreateInputConnection(outAttrs),
true);
}
private class DeleteInputConnection extends InputConnectionWrapper {
public DeleteInputConnection(InputConnection target, boolean mutable) {
super(target, mutable);
}
@Override
public boolean sendKeyEvent(KeyEvent event) {
return super.sendKeyEvent(event);
}
@Override
public boolean deleteSurroundingText(int beforeLength, int afterLength) {
//在删除时,输入框无内容,或者删除以后输入框无内容
if (beforeLength == 1 && afterLength == 0) {
return sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN,
KeyEvent.KEYCODE_DEL))
&& sendKeyEvent(new KeyEvent(KeyEvent.ACTION_UP,
KeyEvent.KEYCODE_DEL));
}
return super.deleteSurroundingText(beforeLength, afterLength);
}
}
}