在 Android 应用中,我们有自定义的 AppCompatDialog
类,需要在关闭对话框后在 EditText
上打开软输入法(键盘)。
为了显示键盘,使用这个函数:
fun View.showKeyboard() = context.inputMethodManager?.let {
// Find the really focused EditText in this root view.
val focusedView = if (this is ViewGroup) this.findFocus() else this
it.showSoftInput(focusedView ?: this, InputMethodManager.SHOW_IMPLICIT)
}
在对话框 OnDismissListener
中,当在 Fragment
中调用下面的代码时,该代码会在 70% 的情况下产生预期的结果,但为了始终模拟器和真实设备,需要为 50ms
添加任意 postDelayed
延迟时间。
view?.post {
binding.input.apply {
// binding.input is our custom Widget that contains EditText
requestFocus()
showKeyboard()
}
}
我希望代码库中没有这个魔术数字,而且我担心,这在某些 Android 发行版中可能不起作用。
是否有更好的经过验证的解决方案,适用于大多数 Android 版本和特定于供应商的发行版?
感谢您的帮助