editText get text kotlin
The voted answer is correct but it is not the best one for the Kotlin's world. If you're really interested in entering into this world, I'd recommend you to use extensions. From Kotlin you have kotlin-android-extensions
and with it you can do this:
import kotlinx.android.synthetic.reference_to_your_view.editTextHello
and this:
Toast.makeText(this, editTextHello.text, Toast.LENGTH_SHORT).show()
please, forget about the getText()... use just this, it is more clean.
ps: read about extensions and you will see you can create your own extensions and do an even more clean usage of the Toast. Something like this:
fun Context.showToast(text: CharSequence, duration: Int = Toast.LENGTH_LONG) = Toast.makeText(this, text, duration).show()
and it being used like this through your classes:
showToast("uhuuu")
but this is beyond the scope we're talking about here.
from: https://kotlinlang.org/docs/tutorials/android-plugin.html
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()
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.