koffyone
koffyone

Reputation: 107

(Android Studio, Kotlin) Image in Imageview is not displaying when clicked

Hi all I have a problem in displaying image in ImageView when clicked, i made a function to display whenever the image was click I have already added the android:onClick="drops" in .xml in every imageview of my sample game, i used gridlayout(3x3) with 9 imageview

enter image description here

here is the code of the function.

    fun drops(view: View){

    val imageView = ImageView(this)

    var player = 0;
    if (player == 0){
        imageView.setImageResource(R.drawable.yellow)
        imageView.animate().alpha(1f).rotation(360f).setDuration(600)
        player == 1
    }else {
        imageView.setImageResource(R.drawable.red)
        imageView.animate().alpha(1f).rotation(360f).setDuration(600)
        player == 0
    }

}

Upvotes: 0

Views: 937

Answers (1)

Andrej Hučko
Andrej Hučko

Reputation: 26

I'm unsure in what class is this function contained, I suppose it is either in a Fragment or Activity. As you said, you're binding the image views with drops method in the xml layout.

What could be the problem is this line:

val imageView = ImageView(this)

From your question we cannot see which class is this method defined in, so expression this could be anything. You might me instantiating an ImageView from the whole Activity or Fragment object, and cannot work in way you would like to. So I suggest to rewrite this line to something like this:

val imageView = view as ImageView

The function drops receives a single View parameter, which is the image view the user clicked - but View class has no method called setImageResource, so you need to cast it to the desired subtype (ImageView is subclass of View). This should do the job.

Upvotes: 1

Related Questions