Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if EditText is empty kotlin android

Tags:

android

kotlin

How do you check if an EditText is empty? input type number

package com.example.www.myapplication

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    button.setOnClickListener {

        val inter:Int=editText.text.toString().toInt()
        val year: Int = Calendar.getInstance().get(Calendar.YEAR)
        val res:Int=year-inter
        textView.text=res.toString()
    }
}
like image 324
mohanad.99 Avatar asked Sep 04 '17 11:09

mohanad.99


People also ask

What does an empty editText return?

It will return true if its empty/null. Show activity on this post.

How do I get rid of editText text in Kotlin?

Use editText. getText(). clear() . This is the correct way to do this.


2 Answers

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()
}
like image 87
Nikhil Katekhaye Avatar answered Sep 17 '22 13:09

Nikhil Katekhaye


Harness Kotlin power by using inline extension functions:

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

or use let

like image 40
Nikola Despotoski Avatar answered Sep 21 '22 13:09

Nikola Despotoski