1.自定义KeyDelEditText
public class KeyDelEditText extends EditText {
private OnKeyListener mKeyListener;
public KeyDelEditText(Context context) {
super(context);
}
public KeyDelEditText(Context context, AttributeSet attrs) {
super(context, attrs);
}
public KeyDelEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public void setOnKeyListener(OnKeyListener l) {
mKeyListener = l;
super.setOnKeyListener(l);
}
@Override
public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
return new InnerInputConnection(super.onCreateInputConnection(outAttrs), true);
}
private class InnerInputConnection extends InputConnectionWrapper {
public InnerInputConnection(InputConnection target, boolean mutable) {
super(target, mutable);
}
@Override
public boolean deleteSurroundingText(int beforeLength, int afterLength) {
boolean ret = false;
if (beforeLength == 1 && afterLength == 0 && mKeyListener != null) {
ret = mKeyListener.onKey(KeyDelEditText.this, KeyEvent.KEYCODE_DEL, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL));
}
return ret || super.deleteSurroundingText(beforeLength, afterLength);
}
}
}
2.替换xml里面的EditText为KeyDelEditText
<com.suyf.view.KeyDelEditText
android:id="@+id/et_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
3.正常方式设置setOnKeyListener事件
EditText etContent = findViewById(R.id.et_content);
etContent.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DEL && event.getAction() == KeyEvent.ACTION_DOWN) {
//处理具体的删除操作
return true;
}
return false;
}
});
和一般的正常情况相比较,修改很少,只需要引入KeyDelEditText这个类,并替换xml文件里面的EditText为KeyDelEditText即可,其他的都不用改动。