我的应用程序中公开了以下 Android Material 组件的下拉菜单:
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/drop_down_menu"
style="@style/Widget.MaterialComponents.TextInputLayout.FilledBox.ExposedDropdownMenu"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_marginEnd="8dp"
android:theme="@style/Theme.MaterialComponents.Light.DarkActionBar"
app:boxBackgroundColor="@android:color/white"
app:layout_constraintBottom_toBottomOf="@+id/number_text_view"
app:layout_constraintEnd_toStartOf="@+id/add_button"
app:layout_constraintTop_toTopOf="@+id/number_text_view">
<com.google.android.material.textfield.MaterialAutoCompleteTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="none"
android:paddingStart="8dp"
android:paddingEnd="8dp" />
</com.google.android.material.textfield.TextInputLayout>
当用户触摸下拉菜单并出现菜单选项时,如何隐藏片段中的软键盘?当用户单击
EditText
组件并且在触摸下拉菜单关闭键盘之前未触摸屏幕的其他部分时,键盘会显示。
您可以将
focusChangeListener
注册到MaterialAutoCompleteTextView
并在获得焦点时隐藏键盘。
autoCompleteTextView.setOnFocusChangeListener { v, hasFocus ->
if (hasFocus) {
hideSoftKeyboard() // Using activity extension function
// v.hideKeyboard() // Using view extension function
}
}
这是隐藏键盘的 Activity 扩展功能:
fun Activity.hideSoftKeyboard() {
val inputMethodManager =
this.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
val currentFocus = this.currentFocus
val windowToken = this.window?.decorView?.rootView?.windowToken
inputMethodManager.hideSoftInputFromWindow(windowToken, 0)
inputMethodManager.hideSoftInputFromWindow(
windowToken,
InputMethodManager.HIDE_NOT_ALWAYS
)
if (currentFocus != null) {
inputMethodManager.hideSoftInputFromWindow(currentFocus.windowToken, 0)
}
}
或者您可以在
View
本身上使用以下内容。
来源
fun View.hideKeyboard(): Boolean {
try {
val inputMethodManager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
return inputMethodManager.hideSoftInputFromWindow(windowToken, 0)
} catch (ignored: RuntimeException) { }
return false
}
}
bindingSheet.dropDownFloorList.setOnFocusChangeListener { v, hasFocus ->
if (hasFocus) {
hideSoftKeyboard() // Using activity extension function
// v.hideKeyboard() // Using view extension function
}
}