[Novice Wang] How do I call up the view id corresponding to a variable?

Asked 2 years ago, Updated 2 years ago, 37 views

I'm making a simple game out of Cotlin at Android Studio.

There are several image buttons, and you want to turn a random number so that the button image corresponding to the number that corresponds to the number that comes out.

Up to 20 numbers and buttons 1:1, command sentence

If(i=1){ button_1.setImageResource(R.drawable.b) }

else if(i=2){ button_2.setImageResource(R.drawable.b) }

else if(i=3) ....

I wrote each and every one of them all

I thought it would be better to make a variable i and let button_n work when the random number i=n, rather than the labor of about 100 buttons.

Just like above, but ton_n.If I setimagerresource(), I can't find button_n. I don't know how to call this upㅠㅠ

android studio

2022-09-22 11:46

1 Answers

getIdentifier() allows you to get the id as the resource name.

fungetImageViewByIdx(idx: Int): ImageView{
    val resId = context.resources.getIdentifier("button_$idx","id", context.packageName)
    return findViewById(resId)
}


2022-09-22 11:46

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.