androidlistkotlinandroid-imagebutton

Detect onclick of any element in a list (android studio)


So I'm working on an app in Android Studio and I'm making a feature where you can set a main image to the image on any button you press.

To check if any item in the list is clicked I'm trying to do something like this (no this isn't actual working code this is just an example of what I'm trying to accomplish): images.setOnClickListener(clickedImage: ImageButton) { and then set the main image to the image clicked (main image.srcCompat = clickedImage.srcCompat }

PS: This is in Kotlin in Android Studio Hedgehog even more PS: I'm just starting out Kotlin so it might've just been a stupid mistake but I don't know the syntax very good.

What I'm guessing is right (and obviously isn't working) is that to make the list I should do this:

val images = listOf( //list containing every single image button available for investment images
        findViewById<ImageButton>(R.id.imageButton1),
        findViewById<ImageButton>(R.id.imageButton2),
        findViewById<ImageButton>(R.id.imageButton3),
        findViewById<ImageButton>(R.id.imageButton4),
        findViewById<ImageButton>(R.id.imageButton5),
        findViewById<ImageButton>(R.id.imageButton6),
        findViewById<ImageButton>(R.id.imageButton7),
        findViewById<ImageButton>(R.id.imageButton8),
        findViewById<ImageButton>(R.id.imageButton9),
        findViewById<ImageButton>(R.id.imageButton10),
        findViewById<ImageButton>(R.id.imageButton11),
        findViewById<ImageButton>(R.id.imageButton12),
        findViewById<ImageButton>(R.id.imageButton13),
        findViewById<ImageButton>(R.id.imageButton14),
        findViewById<ImageButton>(R.id.imageButton15)
    )

Anyone know any functions or any way do to this? I'm basically just trying to detect if any button in a list is clicked and then detect which button it is.


Solution

  • The solution is a for loop. (im an idiot lol)