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()
    }
}

推荐答案

下面是完整的例子和解释.

    //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()
        }
    }

Kotlin相关问答推荐

导入org.gradle.jvm.toolchain.internal.JavaToolchainFactory未解析引用:Java工具链工厂

Kotlin协程挂起继续线程

Kotlin-stdlib中的模拟扩展函数

编译后的JavaFX应用程序立即以静默方式崩溃

有没有一种简单的方法来识别物体?

Kotlin中是否可以混合使用推断和显式的通用类型参数?

用于将 0.5 变为 0 的 round() 函数的模拟

如何规避 Kotlin 的泛型类型差异约束

通用接口继承

在 kotlin 中重载函数时,我在一些非常基本的代码上不断收到类型不匹配

Kotlin 日期格式从一种更改为另一种

如何在 kotlin 中生成 json 对象?

Jetpack Compose State:修改类属性

面临一些未知问题一些后端jvm内部错误

是否在Kotlin中重写enum toString()?

如何为kotlin异常生成SerialVersionId?

如何限制kotlin协程的最大并发性

Kotlin替换字符串中的多个单词

递归方法调用在 kotlin 中导致 StackOverFlowError 但在 java 中没有

在 intelliJ 元素中集成 Kotlinx 协程