在ImageView小部件的findViewById()中获取此错误

时间:2020-10-02 17:38:48

标签: android android-studio kotlin

这是我目前显示图像骰子1的掷骰子应用程序的代码。 findViewById()在textview上正常工作,但是显示图像错误。这行

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

IDE建议创建一个功能。我应该如何解决?我是Kotlin和Android Studio的新手。

package com.unnati.diceroll

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.ImageView

/* these lines allows user to roll the dice and show on the screen */
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val rollButton: Button = findViewById(R.id.button)
        rollButton.setOnClickListener {
            rollDice()
        }
    }  }
//roll the dice and show on the screen
    private fun rollDice() {
        val dice = Dice(6)
        val diceRoll = dice.roll()

        val diceImage: ImageView = findViewById(R.id.imageView)
        diceImage.setImageResource(R.drawable.dice_1)
}



class Dice(val numSides: Int) {
    fun roll(): Int {
        return (1..numSides).random()
    }
}

1 个答案:

答案 0 :(得分:0)

在onCreate()方法而不是rollDice()方法中编写此代码行

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

按如下所示编辑代码

class MainActivity : AppCompatActivity() {

   lateinit var diceImage:ImageView

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

        diceImage = findViewById(R.id.imageView)
        val rollButton: Button = findViewById(R.id.button)
        rollButton.setOnClickListener {
            rollDice(diceImage)
        }
    }  }
//roll the dice and show on the screen
   private fun rollDice(diceImage: ImageView) {
        val dice = Dice(6)
        val diceRoll = dice.roll()
        diceImage.setImageResource(R.drawable.dice_1)
}



class Dice(val numSides: Int) {
    fun roll(): Int {
        return (1..numSides).random()
    }
}```

现在findViewById()将起作用。