【问题标题】:"app keeps stopping" error android studio“应用程序不断停止”错误android工作室
【发布时间】:2021-03-12 13:46:51
【问题描述】:

我正在用 kotlin 编写,我正在创建一个应该掷两个骰子的应用程序。由于我创建了一个名为 randomize 的函数,因此我必须为“textView”(和 textView2)创建一个全局变量。

class MainActivity : AppCompatActivity() {

var textView = findViewById<TextView>(R.id.textView)
var textView2 = findViewById<TextView>(R.id.textView)

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

    textView = findViewById<TextView>(R.id.textView)
    textView2 = findViewById<TextView>(R.id.textView)
    textView.text = randomize()
    textView2.text = randomize()

    val button = findViewById<Button>(R.id.button)
    button.setOnClickListener{
        textView.text = randomize()
        textView2.text = randomize()
    }

    val button2 = findViewById<Button>(R.id.button2)
    button2.setOnClickListener {
        val intent = Intent(Intent.ACTION_VIEW,
                Uri.parse("https://www.google.com/search?q=${textView.text.toString()}+${textView2.text.toString()}"))
        startActivity(intent)
    }


}



private fun randomize() : String{
    return floor((Math.random()*6)+1).toInt().toString()
}

如果我运行模拟器,我得到一个错误“应用程序一直在停止”,如果我查看调试器,我发现错误出现在 textView 和 textView2 的全局初始化中(上面显示的代码的第三和第四行)。

【问题讨论】:

    标签: android-studio class kotlin global-variables


    【解决方案1】:

    我看到问题是

    textView = findViewById<TextView>(R.id.**textView**)
    textView2 = findViewById<TextView>(R.id.**textView**)
    

    对于您调用相同 id 的两个 textview,我想这就是为什么存在问题检查您的 XML 文件并发出正确的 id

    【讨论】:

    • 我按照你说的修改了代码,但仍然没有工作,它给了我同样的错误。
    • 实际上为什么提到你的 textview 2 次?您已经在 oncreate 函数之前调用了它,因此请尝试删除 oncreate 内部的那个,您不必两次调用带有 id 的 textview
    • 仍然无法正常工作。从调试器中,我在同一行看到相同的错误。
    • 那么,当您进行了更改后,您可以使用新代码进行编辑吗?
    猜你喜欢
    • 2015-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-08
    相关资源
    最近更新 更多