繁体   English   中英

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

[英]Hide Soft Keyboard When User Touches the Dropdown Menu

我的应用程序中有以下 Android Material Components 暴露的下拉菜单:

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

这是隐藏键盘的活动扩展 function:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM