【问题标题】:Android App crashes when pressing a Button in Kotlin在 Kotlin 中按下按钮时,Android 应用程序崩溃
【发布时间】:2021-06-19 09:37:20
【问题描述】:

我从 Java 切换到 Kotlin,我是一个全新的人。 我试图制作一个应用程序来计算你的年龄。 age 输入是通过 Android Studio 中的 EditText 输入的。 然后将您的年龄设置为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()

        })

【问题讨论】:

  • val age = edtTxtAge.text.toString().toInt() * minutesPerYear
  • 在此处查看此答案:stackoverflow.com/questions/7200108/…
  • 请显示错误代码。
  • 请提供崩溃的堆栈跟踪。
  • 这是错误日志:NumberFormatException: For input string:

标签: android kotlin crash


【解决方案1】:

初始化年龄时,你必须在调用字符串之前调用“text”:

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

    })

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-16
    相关资源
    最近更新 更多