Android 11及以上 showSoftInput 没有效果解决方式

时间:2025-01-28 10:03:17

笔者在使用带输入框的AlertDialog时需要将输入框立即显示出来,发现在安卓11 (API 30)及以上版本使用传统的显示输入法代码失效,查找后发现新的方式。

问题记录

安卓11 (API 30)及以上版本无法调用以下代码无法显示输入框并在控制台找到以下提示信息。


 binding.editText.requestFocus()
 val imm = requireContext().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
 imm.showSoftInput(binding.editText, InputMethodManager.SHOW_IMPLICIT)

信息提示

 Ignoring showSoftInput() as view=" + view + " is not served

解决方式

使用新的方式代替老方式进行显示输入框。

输入框显示调用
binding.editText.windowInsetsController.show(WindowInsetsCompat.Type.ime())

或者兼容模式

 WindowInsetsControllerCompat(requireDialog().window!!, binding.editText).show(
            WindowInsetsCompat.Type.ime()
        )
输入框隐藏调用
binding.editText.windowInsetsController.hide(WindowInsetsCompat.Type.ime())

或兼容模式

WindowInsetsControllerCompat(requireDialog().window!!, binding.editText).hide(
            WindowInsetsCompat.Type.ime()
        )