如何获取隐藏键盘事件

时间:2018-07-30 14:18:12

标签: android

我想知道如何从我的SoftKeyboard中获取hide事件,该事件在单击EditText(左侧的第一个按钮)时显示:

enter image description here

<EditText
        android:id="@+id/txtEdit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="text|textAutoComplete"
        android:windowSoftInputMode="stateHidden|adjustResize"/>

因为我不想先隐藏键盘,然后在隐藏键盘后,点击“后退”按钮返回。我想立即回去而不先隐藏。

enter image description here

我知道如何从活动中获取back事件:

@Override
public void onBackPressed() {
    // my code
}

但是使用此覆盖,我无法获得hide事件,而只能得到back事件。有人知道如何举办该活动吗?

2 个答案:

答案 0 :(得分:1)

在这段代码中,我在听editText。如果用户关闭键盘,则onBackPressed()将运行。

 var isFirst: Boolean = true

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    editText.getViewTreeObserver().addOnGlobalLayoutListener(ViewTreeObserver.OnGlobalLayoutListener {
        if (isKeyboardOpen()) {
            if (isFirst) {
                 isFirst = false
            }
        } else {
            if (!isFirst) {
                onBackPressed()
            }
        }
    })

}

private fun isKeyboardOpen(): Boolean {
    val r = Rect()
    editText.getWindowVisibleDisplayFrame(r)
    val screenHeight = editText.getRootView().getHeight()
    // r.bottom is the position above soft keypad or device button.
    // if keypad is shown, the r.bottom is smaller than that before.
    val keypadHeight = screenHeight - r.bottom
    // Log.d("TAG", "keypadHeight = $keypadHeight")

    if (keypadHeight > screenHeight * 0.15) { // 0.15 ratio is perhaps enough to determine keypad height.
        // keyboard is opened
        Log.d("TAG", "keypad is open")
    } else {
        // keyboard is closed
        Log.d("TAG", "keypad is close")
    }
    return (keypadHeight > screenHeight * 0.15)
}

override fun onBackPressed() {
    // my code
    Log.d("TAG", "keypad is onBackPressed")
    finish()
}

答案 1 :(得分:0)

单击任何需要用户输入的文件时,键盘就会出现。默认情况下,该键盘是Android操作系统提供的一种。 要自己管理键盘,可以使用底页。为此,您必须制作一个自定义键盘并手动进行每个输入。之后,您可以执行onbackpressed方法来直接返回。

相关问题