Android软键盘:"完成" on" Dismiss"

时间:2016-10-24 10:46:05

标签: android events keyboard event-handling android-softkeyboard

我想处理"关闭软键盘" Android中的事件,据我所知,执行此操作的唯一解决方案是根据this answer创建EditText的子类。

这是我的班级:

public class EditTextCustom extends EditText {

    public EditTextCustom(Context context) {
        super(context);
    }

    public EditTextCustom(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public EditTextCustom(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
        super.onFocusChanged(focused, direction, previouslyFocusedRect);
        if (listener != null)
            listener.onStateChanged(this, true);
    }

    @Override
    public boolean onKeyPreIme(int keyCode, @NonNull KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
            Log.d("Info", "Soft keyboard was hidden");
            if (listener != null) {
                listener.onStateChanged(this, false);
            }
        }
        return super.onKeyPreIme(keyCode, event);
    }

    KeyboardListener listener;

    public void setOnKeyboardListener(KeyboardListener listener) {
        this.listener = listener;
    }

    public interface KeyboardListener {
        void onStateChanged(EditTextCustom keyboardEditText, boolean showing);
    }
}

我需要此事件(KeyEvent.KEYCODE_BACKKeyEvent.ACTION_UP)充当EditorInfo.IME_ACTION_DONE,即当用户解除软键盘时,如果已按下{则由Android解释{1}}已应用"Done"的修改。

实施此方法的最佳做法是什么?

1 个答案:

答案 0 :(得分:-1)

mEtNumber.setOnEditorActionListener(new TextView.OnEditorActionListener() {

        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                // do something, e.g. set your TextView here via .setText()
                InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                return true;
            }
            return false;
        }
    });

mEtNumber.setOnEditorActionListener(new TextView.OnEditorActionListener(){

        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                // do something, e.g. set your TextView here via .setText()
                InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                return true;
            }
            return false;
        }
    });

和xml

机器人:imeOptions = “actionDone”

这可能会对你有帮助。