Android软键盘-使用onbackpressed方法

时间:2019-06-13 04:56:10

标签: android kotlin

当我按下Android手机上的后退按钮时,它会关闭软键盘,但是当调用onbackpressed方法时,它不会关闭软键盘

我试图以编程方式关闭软键盘,但无法完全解决问题

val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager

    if (imm.isAcceptingText){
        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0)
        android.R.id.accessibilityActionHideTooltip

    }*

我想在调用onbackpressed方法时关闭软键盘,后退按钮在Android中到底如何工作?

如果我调用onbackpressed方法,则需要以编程方式关闭软键盘,我需要避免那种关闭键盘代码

1 个答案:

答案 0 :(得分:1)

这应该关闭键盘

    window!!.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN)

或创建一个函数

fun hideKeyboard(activity: Activity) {
    val imm = activity.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
    //currently focused view
    var view = activity.currentFocus
    //If null, create a new one
    if (view == null) {
        view = View(activity)
    }
    imm.hideSoftInputFromWindow(view.windowToken, 0)
}

并致电

    hideKeyboard(your_activity_context as YourActivity)