Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
like image 361
user2661518 Avatar asked May 30 '17 16:05

user2661518


2 Answers

This is Kotlin, not java. You do not need to get the id of it. In kotlin, just write:

var editTextHello = editTextHello.text.toString()

use the beauty of kotlin ;-)

P.s: BTW, better to choose xml IDs like edx_hello and for the kotlin part, var editTextHello. Then you can differentiate between xml vars and kotlin vars.

like image 81
Mehran Avatar answered Sep 19 '22 17:09

Mehran


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()
like image 25
zsmb13 Avatar answered Sep 19 '22 17:09

zsmb13