如何用键盘回车关闭AlertDialog?

How to close AlertDialog with keyboard Enter?

目前,当我在 editText 字段中输入文本并按下键盘上的 Enter 键时,它会按预期更改我的文本,但 AlertDialog 会保留在屏幕和键盘上。有没有办法在我按下回车键时关闭警报和键盘? alertDialog.dismiss()alertDialog.close() 对我不起作用。谢谢你的时间。

(1..912).forEach {
        val id = resources.getIdentifier("Price$it", "id", packageName)
        val tv = findViewById<TextView>(id)
        tv.setOnLongClickListener {

            //Alert Window
            val alertDialog = AlertDialog.Builder(this@MainActivity)
            alertDialog.setTitle("NEW PRICE")
            val input = EditText(this@MainActivity)
            //Alert Submit on Enter
            input.setOnKeyListener { v, keyCode, event ->
                if (event.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {
                    // Input changes text
                    tv.text = input.text
                    when {
                        tv.text.startsWith("-") -> tv.setTextColor(Color.RED)
                        tv.text.startsWith("+") -> tv.setTextColor(Color.GREEN)
                    else -> {
                        tv.text = "_"
                        tv.setTextColor(Color.DKGRAY)
                    }
                    }
                    // Close Alert Window
                    alertDialog.dismiss()


                    // Save Price Table
                }
                false
            }


            val lp = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT
            )
            input.layoutParams = lp
            alertDialog.setView(input).show()
            return@setOnLongClickListener true

        }
    }

您已将 alertDialog 声明为 AlertDialog.Builder 而不是 AlertDialog
AlertDialog.Builder 没有 dismiss() 方法。
变化:

val alertDialog = AlertDialog.Builder(this@MainActivity)

val alertDialog = AlertDialog.Builder(this@MainActivity).create()

alertDialog.setView(input).show()

alertDialog.setView(input)
alertDialog.show()