Android 在 Kotlin 中按下按钮时应用崩溃

Android App crashes when pressing a Button in Kotlin

我从 Java 切换到 Kotlin,我是全新的。 我试图制作一个可以计算你的年龄的应用程序。 age 输入是通过 EditText 在 Android Studio 中进行的。 然后把你的年龄设置成TextView.

当我按下应用程序崩溃的按钮时。 下面是 Kotlin 代码


        var edtTxtAge = findViewById<EditText>(R.id.edtTxtAge)
        val btnCalc = findViewById<Button>(R.id.btnCalc)
        var txtAge = findViewById<TextView>(R.id.txtAge)

        btnCalc.setOnClickListener(View.OnClickListener {

            val minutesPerYear = 525600
            val age = edtTxtAge.toString().toInt() * minutesPerYear
            txtAge.text = "Your age in minutes is: " + age.toString()

        })

初始化 age 时必须先调用“text”再调用 string:

var edtTxtAge = findViewById<EditText>(R.id.edtTxtAge)
    val btnCalc = findViewById<Button>(R.id.btnCalc)
    var txtAge = findViewById<TextView>(R.id.txtAge)

    btnCalc.setOnClickListener(View.OnClickListener {

        val minutesPerYear = 525600
        val age = edtTxtAge.text.toString().toInt() * minutesPerYear
        txtAge.text = "Your age in minutes is: " + age.toString()

    })