Home > Enterprise >  How to refer to a button that is in the list Kotlin
How to refer to a button that is in the list Kotlin

Time:08-17

I am trying to create an app in android studio. I've only recently started to get interested in this and ran into a problem. As planned, for each move in the game, the player presses several buttons, I would like to put the id of these buttons in a separate list, and when necessary, use this list to change the color of all those buttons that are in this list

What i did:

I have the list->

val move_list: MutableList<Any> = mutableListOf()

When the player presses the button, I add its id to move_list

fun for_btn_buba2(view: View){
    move_list.add(buba2.id)

In activity_main.xml my button seems like:

<Button
    android:id="@ id/buba2"
    android:text="Buba 2"
    ...
    android:onClick="for_btn_buba2"/>

And on click of another button i wanted to insert code like this:

move_list[0].setBackgroundColor(Color.parseColor(colorString:"#FFFC9D45"))

move_list[0] means id for button buba2

In python it can be, but it isnt python)

How can I change the color of the button through the list index with the buttons?

CodePudding user response:

Firstly I suggest you indicate the type of what is in the list, which is Int so like

val move_list: MutableList<Int> = mutableListOf()

Then you can probably do this in the onClick of the other button

findViewById<View>(move_list[0]).setBackgroundColor(Color.parseColor("#FFFC9D45"))

or to do it to all

move_list.forEach { 
    findViewById<View>(it).setBackgroundColor(Color.parseColor("#FFFC9D45"))
}

I also notice you directly refer to buba2 in it the for_btn_buba2. I have the feeling that you are writing this function for every buba. This is unnecessary. You can get the id from the view parameter because that is in fact the same id. So do

fun for_btn_buba(view: View){
    move_list.add(view.id)
}

then you can give each buba the same for_btn_buba as android:onClick


Alternatively you don't even work with ids at all and make it a

val move_list: MutableList<View> = mutableListOf()

and then do

fun for_btn_buba(view: View){
    move_list.add(view)
}

and then you can actually change the background like you wrote it:

move_list[0].setBackgroundColor(Color.parseColor("#FFFC9D45"))

or

move_list.forEach { 
    it.setBackgroundColor(Color.parseColor("#FFFC9D45"))
}
  • Related