I’m just new to Kotlin and Android Studio.
I’m trying to access the text of the input (editText) and do some processing before showing it, but I’m not able to do it.
I’m trying three different "variations", but any of them work.
.xml
<EditText
android:id="@+id/placa"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="@string/placa"
android:autofillHints=""
android:layout_gravity="center_horizontal"
android:inputType="text"/>
Kotlin:
// Objects
val button: Button = findViewById(R.id.consultar)
val editTextPlaca: EditText = findViewById(R.id.placa)
// Strings
val placa = editTextPlaca.text
val placa2 = editTextPlaca.text.toString()
val placa3 = editTextPlaca.getText().toString()
// Process String
val mensaje = "The plate is " + placa + placa2 + placa3
button.setOnClickListener {
Toast.makeText(this, mensaje, Toast.LENGTH_SHORT).show()
}
The output I get is just: "The plate is "
Thanks for your help.
2
Answers
You’re assigning the value to the string variables
placa
,placa2
, andplaca3
before the button clicks even if the user has not entered any text in theEditText
.Read the value from
EditText
when the button is clicked.Note: I have used the
$
operator to concatenate the text.You have this output because you extracted the text at the very beginning, not at the moment of the button click.
By the way, Kotlin has a handy String interpolation feature, so you don’t have to concatenate it with ‘+’. You can do something like this: