Home > Blockchain >  Kotlin- a type annotation is required on a value parameter
Kotlin- a type annotation is required on a value parameter

Time:12-16

So I am not new to programming but new to Java and currently learning Kotlin through a course provided by Google. I reached the Dice Roller app and decided to do the practice on your on challenges at the end of each session where I have to roll 2 dices with 1 roll button but can not do that.

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(dice1) };  **//Error**
        rollButton.setOnClickListener{ rollDice(dice2) };  **//Error**

    }
    private fun rollDice(dice: ImageView) {

        val myDice = Dice(6);
        val diceRoll: Int = myDice.roll();
        val diceImage: ImageView = findViewById(R.id.dice)  **//ERROR**
        diceImage.contentDescription = diceRoll.toString()

        val drawableResource = when (diceRoll) {
            1 -> R.drawable.dice_1
            2 -> R.drawable.dice_2
            3 -> R.drawable.dice_3
            4 -> R.drawable.dice_4
            5 -> R.drawable.dice_5
            else -> R.drawable.dice_6
        }
        diceImage.setImageResource(drawableResource)
        }}

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

}

CodePudding user response:

You have modified your rollDice function to take an ImageView parameter, so you can delete this line:

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

and you can change the line where you set the image to use the parameter that you passed to the function (you named it dice):

dice.setImageResource(drawableResource)

When you call this function, you have to pass the ImageView, so you need to create variables to find those ImageViews before passing them. Also, you can only set one click listener at a time. You need to call the rollDice function twice inside a single click listener. The way you're trying to do it, the first click listener gets erased when you set the second one.

val dice1: ImageView = findViewById(R.id.dice1)
val dice2: ImageView = findViewById(R.id.dice2)

rollButton.setOnClickListener{ 
    rollDice(dice1) 
    rollDice(dice2) 
}
  • Related