当底部的 EditText 时隐藏软键盘不起作用 sheet

Hide soft keyboard not working when EditText in bottom sheet

我在 BottomSheet 中有 EditText。当 BottomSheet 显示并且我点击 EditText 时,就会显示软键盘。但是BottomSheet中Edittext的值长度为6时,如何隐藏软键盘呢?

我有这样的逻辑:

private fun showBottomSheet() {
        val binding: BottomSheetSetupEasyPinBinding =
            DataBindingUtil.inflate(LayoutInflater.from(activity), R.layout.bottom_sheet_setup_easy_pin, null, false)
        binding.fragment = this
        binding.vm = vm
        binding.lifecycleOwner = this

        //For hide softKeyboard
        binding.etEasyPinConfirmation.addTextChangedListener(object : TextWatcher {

            override fun afterTextChanged(s: Editable) {
            }

            override fun beforeTextChanged(s: CharSequence, start: Int,
                                           count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence, start: Int,
                                       before: Int, count: Int) {
                if (s.length == 6) {
                    hideSoftKeyboard()
                    Toast.makeText(activity, "Length is 6", Toast.LENGTH_SHORT).show()
                }
            }
        })

        bottomSheet.setContentView(binding.root)
        bottomSheet.setCancelable(false)
        bottomSheet.show()
    }

这是隐藏软键盘的函数:

fun hideSoftKeyboard() {
        inputMethodManager.hideSoftInputFromWindow(view!!.windowToken, 0)
    }

这是onViewCreated中的全局变量和变量声明:

// global variable
private lateinit var inputMethodManager : InputMethodManager
..
// in onViewCreated
inputMethodManager = requireActivity().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager

但是当EditText的值长度为6时,显示的是Toast,我已经调试过了,函数执行了,但是键盘没有隐藏。有谁知道为什么我的代码无法在 BottomSheet 中隐藏软键盘?因为如果EditText不在BottomSheet中,这个函数隐藏软键盘就成功了

使用这个更新的方法 kotlin 版本

    fun Activity.hideKeyboard() {
    hideKeyboard(currentFocus ?: View(this))
    }

    fun Context.hideKeyboard(view: View) {
    val inputMethodManager = getSystemService(Activity.INPUT_METHOD_SERVICE) as 
    InputMethodManager
    inputMethodManager.hideSoftInputFromWindow(view.windowToken, 0)
    }

在继续进一步检查之前,您是否在单击它时收到编辑文本或按钮的事件,尝试在 addTextChangedListener() 中打印日志。

我认为你没有理解我之前遇到的这个问题。

我刚刚使用了下一个代码:

fun hideSoftKeyboardBottomSheet(view: View) {
    inputMethodManager.hideSoftInputFromWindow(view.windowToken, 0)
}

并将底部视图 Sheet 插入此函数