【问题标题】:Unresolved reference: findViewById未解决的参考:findViewById
【发布时间】: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()
        }
    }

【问题讨论】:

  • findViewByIdActivity 的方法...所以显然你不能在顶级函数中使用它... prolly 这只是一个错字,你应该将括号从之前移到函数之后

标签: android android-studio kotlin findviewbyid


【解决方案1】:

放函数

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

MainActivity 类内部。

【讨论】:

  • 谢谢!这解决了它
【解决方案2】:

把代码改成这个

private fun rollDice(mainActivity: MainActivity ) {
    val dice = Dice(6)
    val diceRoll = dice.roll()
    val diceImage = mainActivity.findViewById<ImageView>(R.id.imageView)
    diceImage.setImageResource(R.drawable.dice_2)
    }

只需在 MainActivity 类中编写函数

【讨论】:

    【解决方案3】:

    更改这行代码:

    val diceImage = findViewById<ImageView>(R.id.imageView)
    

    到这里:

    val diceImage: ImageView = findViewById(R.id.imageView)
    

    【讨论】:

    • 绝对错误的答案不会有任何改变。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-05
    • 1970-01-01
    • 2021-08-17
    • 2016-12-14
    • 2020-05-27
    • 2019-11-16
    • 2021-01-24
    相关资源
    最近更新 更多