取消键盘时使EditText失去焦点

时间:2018-08-09 14:38:32

标签: android kotlin android-edittext

我想通过单击完成按钮或返回按钮来关闭键盘时实现不对焦 EditText(不隐藏光标)的简单任务。到目前为止,我只能找到

window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)

但这仅在首次打开活动时才有用。关闭键盘后,文本字段将处于尴尬的聚焦状态。

4 个答案:

答案 0 :(得分:3)

关闭键盘后,您可以监听某个事件,然后在事件发生时使用editText.clearFocus();

请参阅this answer以收听键盘关闭事件

答案 1 :(得分:0)

您可以从编辑文本中清除焦点,还可以管理启用/禁用编辑文本。

答案 2 :(得分:0)

我不敢相信这是我可以找到的最简单的解决方案(真的是Android吗?):

public class CustomEditText extends EditText {

    public CustomEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.setOnEditorActionListener(new OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == KeyEvent.KEYCODE_ENDCALL) {
                    InputMethodManager imm = (InputMethodManager)v.getContext()
                        .getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(CustomEditText.this.getWindowToken(), 0);
                    CustomEditText.this.clearFocus();
                    return true;
                }
                return false;
            }
        });
    }

    @Override
    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
            this.clearFocus();
        }
        return super.onKeyPreIme(keyCode, event);
    }

}

答案 3 :(得分:0)

科特林版本:

class CustomEditText: AppCompatEditText {
    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
    constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle)

    override fun onKeyPreIme(keyCode: Int, event: KeyEvent?): Boolean {
        if(keyCode == KeyEvent.KEYCODE_BACK) {
            clearFocus()
        }
        return super.onKeyPreIme(keyCode, event)
    }
}

用法:

<com.youappdomain.view.CustomEditText
      android:layout_width="match_parent"
      android:layout_height="wrap_content" />