Android:检测打开的键盘,onApplyWindowListener 不起作用

And*_*rew 6 android android-layout kotlin

我试图在打开键盘时隐藏布局底部的一个特定按钮,以便为用户提供更多视图。

随着androidx.core:core-ktx:1.5.0-alpha02google的发布(最终)添加了一个调用的方法insets.isVisible(WindowInsetsCompat.Type.ime()),无论键盘是打开还是点击,它都会返回一个布尔值。

我正在使用一个基类EmailFragment,我在其中设置了函数以实现上述编写的功能。我的问题是我ViewCompat.setOnApplyWindowInsetsListener(view)从未被调用过(没有吐司等)。

我也尝试ViewCompat.setOnApplyWindowInsetsListener(view)直接在使用过的 Fragments 中进行设置,但这没有任何改变。

我的最小 API 是 21,在我的 AndroidManifest.XML 中有 android:windowSoftInputMode = adjustResize

代码

abstract class EmailFragment<out T: ViewDataBinding>(
    layout: Int,
    // ... some other stuff that is not necessary for the question
) : BaseFragment<T>(layout) {
    // ... some other stuff that is not necesarry for the question

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        hideButton(view)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return super.onCreateView(inflater, container, savedInstanceState)
    }

    
    private fun hideButton(view: View) {
        ViewCompat.setOnApplyWindowInsetsListener(view) { v, insets ->
            val isKeyboardVisible = insets.isVisible(WindowInsetsCompat.Type.ime())
            if (isKeyboardVisible) {
                btn.visibility = View.GONE
                Toast.makeText(requireContext(), "KEYBOARD OPEN", Toast.LENGTH_SHORT).show()
            } else {
                btn.visibility = View.VISIBLE
                Toast.makeText(requireContext(), "KEYBOARD CLOSED", Toast.LENGTH_SHORT).show()
            }

            // Return the insets to keep going down this event to the view hierarchy
            insets
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

从 EmailFragment 继承的片段(五分之一)

class CalibrateRepairMessageFragment(
    //... some other stuff that is not necessary for this question
) : EmailFragment<FragmentCalibrateRepairMessageBinding>(
    R.layout.fragment_calibrate_repair_message,
    //... some other stuff that is not necessary for this question
) {
    //... some other stuff that is not necessary for this question

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        //... some other stuff that is not necessary for this question
    }
Run Code Online (Sandbox Code Playgroud)

截图 1(审查)

在此处输入图片说明

截图 2,不工作(审查)

在此处输入图片说明

我知道使用android:windowSoftInputMode = adjustPen会使我的按钮“不可见”,但随后我无法再滚动,非常难过..

另一种解决方案可能是键盘只是与按钮重叠,但我不知道如何做到这一点......

我感谢每一个帮助,谢谢。

Mid*_*fko 3

我能够通过以下方式让它发挥作用:

  1. 添加android:windowSoftInputMode="adjustResize"Activity清单中的标签
  2. 设置OnApplyWindowInsetsListenerwindow.decorView.

然而,这对状态栏产生了不幸的副作用,这意味着OP的评论(“我不希望这会起作用”)可能是准确的。希望它在从 alpha 和 beta 版毕业后能够发挥作用。