【发布时间】:2021-04-08 14:05:40
【问题描述】:
我目前正在学习 Google android 开发人员课程,并尝试使用骰子应用程序,但在调用 findViewById 方法时,它一直给我一个错误。我不知道为什么,特别是因为我已经为按钮调用了这个方法。
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val rollButton = findViewById<Button>(R.id.button)
rollButton.setOnClickListener { rollDice() }
}
}
private fun rollDice() {
val dice = Dice(6)
val diceRoll = dice.roll()
val diceImage = findViewById<ImageView>(R.id.imageView) //error comes up on this line
diceImage.setImageResource(R.drawable.dice_2)
}
class Dice(private val numSides: Int) {
fun roll(): Int {
return (1..numSides).random()
}
}
【问题讨论】:
-
findViewById是Activity的方法...所以显然你不能在顶级函数中使用它... prolly 这只是一个错字,你应该将括号从之前移到函数之后
标签: android android-studio kotlin findviewbyid