0

Hey I'm just a week into Kotlin but I'm struggling with something now. I got this list where I want to put 20 ImageButtons in efficiently with not writing everything individually. I gave all ImageButtons an id that only differs with an integer at the end, for example: takLinks1, takLinks2, takLinks3, ...

I'm trying to do it with a while loop but I can't seem to find the right syntax for Kotlin to do it. Does anyone have an idea how I could tackle this?

private lateinit var takkenLinks: ArrayList<ImageButton>
private fun populateButtonList(){
    var i = 1
    while (i < 21) {
        val takLinks$i = findViewById<ImageButton>(R.id."takLinks$i")
        takkenLinks.add(taklinks$i)
    }
}
2
  • The better way to do this is instead of putting all the buttons in your layout, put a RecyclerView in your Layout and create your Buttons in the RecyclerView.Adapter. It's not trivial to learn how to use RecyclerView, but you eventually will have to learn it anyway since it is so widely used. Commented Feb 19, 2022 at 14:52
  • Thanks for the tip! I'll take a look at it Commented Feb 19, 2022 at 14:56

1 Answer 1

0

I eventually landed on this code for now, making an array of id's and then just loop through the array and adding each id to the ArrayList and this seems to do the trick. ( I also divided the 20 to 2 sets of 10 )

private fun populateButtonList(){
    val idL = arrayOf(R.id.takLinks1, R.id.takLinks2, R.id.takLinks3, R.id.takLinks4, R.id.takLinks5,
            R.id.takLinks6, R.id.takLinks7, R.id.takLinks8, R.id.takLinks9, R.id.takLinks10)
    val idR = arrayOf(R.id.takRechts1, R.id.takRechts2, R.id.takRechts3, R.id.takRechts4, R.id.takRechts5,
            R.id.takRechts6, R.id.takRechts7, R.id.takRechts8, R.id.takRechts9, R.id.takRechts10)
    var i = 0
    while (i < 10) {
        val takLinks = findViewById<ImageButton>(idL[i])
        val takRechts = findViewById<ImageButton>(idR[i])
        giveClickListeners(takLinks, i, "wij")
        giveClickListeners(takRechts, i, "zij")
        takkenLinks.add(takLinks)
        takkenRechts.add(takRechts)
        i += 1
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.