Check if EditText is empty kotlin android

Here is the full example with explanation.

    //init the edittext
    val etMessage = findViewById(R.id.et_message) as EditText
    //init the button
    val btnClick = findViewById(R.id.btn_click) as Button

    btnClick.setOnClickListener{
        //read value from EditText to a String variable
        val msg: String = etMessage.text.toString()

        //check if the EditText have values or not
        if(msg.trim().length>0) {
            Toast.makeText(applicationContext, "Message : "+msg, Toast.LENGTH_SHORT).show()
        }else{
            Toast.makeText(applicationContext, "Please enter some message! ", Toast.LENGTH_SHORT).show()
        }
    }

You can be done by below way

if (mEdtDeviceName.text.toString().trim().isNotEmpty() || 
    mEdtDeviceName.text.toString().trim().isNotBlank()) {
       // your code
} else {
    Toast.makeText(activity, "Error Msg", Toast.LENGTH_SHORT).show()
}

Harness Kotlin power by using inline extension functions:

editText.text.isNotEmpty().apply { 
    //do something
 }

or use let

Tags:

Android

Kotlin