最近项目中需要加入仿照支付宝文本输入框,从网上找了些例子,但是发现,部分手机无法监听到返回键 ,于是尝试自定义了EditText文本框 直接上代码
import android.content.Context;importandroid.support.annotation.Nullable;
import android.util.AttributeSet;importandroid.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputConnection;importandroid.widget.EditText;
import android.view.View;
/*** Created by Angelfishli on 2017/4/11.*/
public class DetectDelEventEditText extends EditTextimplementsView.OnKeyListener , EditableInputConnection.OnDelEventListener
{
privateDelEventListenerdelEventListener;
/*** 防止delEvent触发两次。* 0:未初始化;1:使用onKey方法触发;2:使用onDelEvdent方法触发*/
private intflag;
publicDetectDelEventEditText(Context context) {
super(context);
init();
}
public DetectDelEventEditText(Context context,@NullableAttributeSet attrs) {
super(context,attrs);
init();
}
public DetectDelEventEditText(Context context,@NullableAttributeSet attrs, intdefStyleAttr) {
super(context,attrs,defStyleAttr);
init();
}
private voidinit() { setOnKeyListener(this);
}
@Override
public InputConnectionon CreateInputConnection(EditorInfo outAttrs) {
super.onCreateInputConnection(outAttrs);
EditableInputConnection editableInputConnection =newEditableInputConnection(this);
outAttrs.initialSelStart= getSelectionStart();
outAttrs.initialSelEnd= getSelectionEnd();
outAttrs.initialCapsMode= editableInputConnection.getCursorCapsMode(getInputType());
editableInputConnection.setDelEventListener(this);
flag=0;
returned itableInputConnection;
}
public void setDelListener(DelEventListener l) {
delEventListener= l;
}
@Override
public boolean onKey(View v, intkeyCode,KeyEvent event) {
if(flag==2) {
return false;
}
flag=1;
returnd elEventListener!=null&& keyCode == KeyEvent.KEYCODE_DEL&& event .getAction() == KeyEvent.ACTION_DOWN&&delEventListener.delEvent();
}
@Override
public boolean onDelEvent() {
if(flag==1) {
return false;
}
flag=2;
returnde lEventListener!=null&&delEventListener.delEvent();
}
public interface DelEventListener {
booleandelEvent();
}
}
效果图