randbo
randbo

Reputation: 36

How to close AlertDialog with keyboard Enter?

Currently when i enter text in the editText field and hit enter on the keyboard it changes my text as intended but the AlertDialog stays on screen as well as the keyboard. Is there a way i can close the Alert and keyboard when i hit enter? alertDialog.dismiss() or alertDialog.close() does not work for me. Thanks for your time.

(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

        }
    }

Upvotes: 0

Views: 878

Answers (1)

forpas
forpas

Reputation: 164069

You have declared alertDialog as AlertDialog.Builder and not AlertDialog.
There is no dismiss() method for AlertDialog.Builder.
Change:

val alertDialog = AlertDialog.Builder(this@MainActivity)

to

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

and

alertDialog.setView(input).show()

to

alertDialog.setView(input)
alertDialog.show()

Upvotes: 1

Related Questions