【发布时间】: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