如何使用键盘Enter关闭AlertDialog?

时间:2019-01-09 22:50:37

标签: kotlin alertdialog dismiss

当前,当我在editText字段中输入文本并按键盘上的Enter键时,它会按预期更改我的文本,但AlertDialog和键盘一样会保留在屏幕上。当我按Enter键时,是否可以关闭警报和键盘? 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

        }
    }

1 个答案:

答案 0 :(得分:1)

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

val alertDialog = AlertDialog.Builder(this@MainActivity)

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

alertDialog.setView(input).show()

alertDialog.setView(input)
alertDialog.show()