Close/Hide SoftinputKeyboard in kotlin
我有一个按钮和edittext。 当用户在edittext中完成输入并按下按钮时,我想关闭我的软键盘。
或其任何指南或参考链接。
调用此函数可隐藏系统键盘:
1 2 3 4 | fun View.hideKeyboard() { val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm.hideSoftInputFromWindow(windowToken, 0) } |
我略微修改了@Serj Ardovic的回应
1 2 3 4 5 6 | private fun hideKeyboard(view: View) { view?.apply { val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm.hideSoftInputFromWindow(view.windowToken, 0) } } |
因为它真的适合我的要求
您可以使用新功能扩展所有
1 | editText.hideSoftKeyboardOnFocusLostEnabled(true) |
在
1 2 3 4 5 6 7 | fun EditText.hideSoftKeyboardOnFocusLostEnabled(enabled: Boolean) { val listener = if (enabled) OnFocusLostListener() else null onFocusChangeListener = listener } |
这是
1 2 3 4 5 6 7 8 | class OnFocusLostListener: View.OnFocusChangeListener { override fun onFocusChange(v: View, hasFocus: Boolean) { if (!hasFocus) { val imm = v.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm.hideSoftInputFromWindow(v.windowToken, 0) } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | fun hideSoftKeyboard(mActivity: Activity) { // Check if no view has focus: val view = mActivity.currentFocus if (view != null) { val inputManager = mActivity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager inputManager.hideSoftInputFromWindow(view.windowToken, 0) } } fun showKeyboard(yourEditText: EditText, activity: Activity) { try { val input = activity .getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager input.showSoftInput(yourEditText, InputMethodManager.SHOW_IMPLICIT) } catch (e: Exception) { e.printStackTrace() } } |