我的布局中有一个EditText和一个Button。
在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?
我的布局中有一个EditText和一个Button。
在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?
当前回答
只需在特定活动的AndroidManifest中添加以下行。
<activity
android:name=".MainActivity"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustPan"/>
其他回答
您可以使用下面的扩展来隐藏和显示软键盘
fun Fragment.showKeyboard(view: View) {
view.isFocusableInTouchMode = true
view.requestFocus()
val imm = view.context?.getSystemService(Context.INPUT_METHOD_SERVICE)
as InputMethodManager
imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT) }
fun Fragment.hideKeyboard(view: View) {
view.clearFocus()
val imm = view.context?.getSystemService(Context.INPUT_METHOD_SERVICE)
as InputMethodManager
imm.hideSoftInputFromWindow(view.windowToken, 0) }
要调用扩展,只需按照以下片段进行操作
showKeyboard(Your edittext ID)
hideKeboard(Your edittext ID)
碎片形式的科特林溶液:
fun hideSoftKeyboard() {
val view = activity?.currentFocus
view?.let { v ->
val imm =
activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager // or context
imm.hideSoftInputFromWindow(v.windowToken, 0)
}
}
检查您的清单是否没有与活动关联的此参数:
android:windowSoftInputMode="stateAlwaysHidden"
使用这个
this.getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
有时你只需要按回车键来折叠键盘在“编辑文本”框中指定属性
android:imeOptions="actionDone"
这将将Enter按钮更改为Done按钮,该按钮将关闭键盘。
您也可以使用此代码段在Kotlin中隐藏键盘。
fun hideKeyboard(activity: Activity?) {
val inputManager: InputMethodManager? =
activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as?
InputMethodManager
// check if no view has focus:
val v = activity?.currentFocus ?: return
inputManager?.hideSoftInputFromWindow(v.windowToken, 0)
}