Получение этой ошибки в findViewById() в виджете ImageView

#android #android-studio #kotlin

#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:

напишите эту строку кода внутри метода 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() будет работать.

Комментарии:

1. Теперь он показывает ошибку с помощью строки diceImage.setImageResource(R.drawable.dice_1) IDE предлагает создать имя функции ‘diceImage’