仿支付宝EditText 部分手机监听不到删除键

    xiaoxiao2021-04-17  32

    最近项目中需要加入仿照支付宝文本输入框,从网上找了些例子,但是发现,部分手机无法监听到返回键 ,于是尝试自定义了EditText文本框 直接上代码

    import android.content.Context; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.KeyEvent; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputConnection; import android.widget.EditText; import android.view.View; /** * Created by Angelfishli on 2017/4/11. */ public class DetectDelEventEditText extends EditText implements View.OnKeyListener, EditableInputConnection.OnDelEventListener { private DelEventListener delEventListener; /** * 防止delEvent触发两次。 * 0:未初始化;1:使用onKey方法触发;2:使用onDelEvdent方法触发 */ private int flag; public DetectDelEventEditText(Context context) { super(context); init(); } public DetectDelEventEditText(Context context, @Nullable AttributeSet attrs) { super(context, attrs); init(); } public DetectDelEventEditText(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { setOnKeyListener(this); } @Override public InputConnection onCreateInputConnection(EditorInfo outAttrs) { super.onCreateInputConnection(outAttrs); EditableInputConnection editableInputConnection = new EditableInputConnection(this); outAttrs.initialSelStart = getSelectionStart(); outAttrs.initialSelEnd = getSelectionEnd(); outAttrs.initialCapsMode = editableInputConnection.getCursorCapsMode(getInputType()); editableInputConnection.setDelEventListener(this); flag = 0; return editableInputConnection; } public void setDelListener(DelEventListener l) { delEventListener = l; } @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (flag == 2) { return false; } flag = 1; return delEventListener != null && keyCode == KeyEvent.KEYCODE_DEL && event .getAction() == KeyEvent.ACTION_DOWN && delEventListener.delEvent(); } @Override public boolean onDelEvent() { if (flag == 1) { return false; } flag = 2; return delEventListener != null && delEventListener.delEvent(); } public interface DelEventListener { boolean delEvent(); } }

    效果图 

    转载请注明原文地址: https://ju.6miu.com/read-673382.html

    最新回复(0)