当用户触摸下拉菜单时隐藏软键盘

Hide Soft Keyboard When User Touches the Dropdown Menu

我的应用程序中显示了以下 Android 材质组件下拉菜单:

<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 本身上使用以下内容。 Source

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
    }
}