Search code examples
android-edittextkotlin

editText get text kotlin


How to get editText in kotlin and display with toast.

var editTextHello = findViewById(R.id.editTextHello)

I tried this but shows object

Toast.makeText(this,editTextHello.toString(),Toast.LENGTH_SHORT).show()

Solution

  • You're missing a cast of the View you get from findViewById to EditText:

    var editTextHello = findViewById(R.id.editTextHello) as EditText
    

    Then, you want to display the text property of the EditText in your toast:

    Toast.makeText(this, editTextHello.text, Toast.LENGTH_SHORT).show()
    

    For the record, this is just the more idiomatic Kotlin equivalent to calling getText() on your EditText, like you'd do it in Java:

    Toast.makeText(this, editTextHello.getText(), Toast.LENGTH_SHORT).show()