So, Just started working with Kotlin in Android Studio 3.0 Canary 7 and I was carrying out a simple operation of checking if string is empty or not.
Here's my simple layout:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click me"
android:id="@+id/btnClick"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Write something to print"
android:id="@+id/edtTxt"/>
and with MainActivity.kt I've below stuff
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
btnClick.setOnClickListener {
val message=edtTxt.text
if (message == "")
longToast("Come on! Write something")
else
longToast("You've written $message")
}
}
}
So initially I've written code within clicklistener as
val message=edtTxt.text
if (message.equals("")) //this here
longToast("Come on! Write something")
else
longToast("You've written $message")
Later on the IDE suggested to replace it with
and I tried on doing that with if (message=="")
but that started showing Operator '==' cannot be applied to 'Editable!' and 'String' when comparing string error. This is totally confusing.
My doubts here:
edtTxt.text
is just a replacement for java's editTxt.getText()
. So basically this has to be converted to String
before using ==
operator.
If you want to get the String from the Editable
object use toString()
method.
val message=edtTxt.text.toString()
btnClick.setOnClickListener {
// edtTxt.text type of EditText
val message=edtTxt.text.toString()
if (message == "")
longToast("Come on! Write something")
else
longToast("You've written $message")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With