I’m noob in android developing. I’m writing fitness application’s page with trainig excercises. I have many buttons clicking on I want to show popup containing some content different to each button. I have this kode:
val button4day2: Button = view.findViewById(R.id.watch4day2)
button4day2.setOnClickListener(){
makePopupDescription(context, R.drawable.pullupsgif,
context.getString(R.string.pullups_description))
}
val button5day2: Button = view.findViewById(R.id.watch5Day2)
button5day2.setOnClickListener(){
makePopupDescription(context, R.drawable.triceps_press,
context.getString(R.string.triceps_press_description))
}
val button1day3: Button = view.findViewById(R.id.watch1Day3)
button1day3.setOnClickListener(){
makePopupDescription(context, R.drawable.warmupgif,
context.getString(R.string.warmup_description))
}
val button2day3: Button = view.findViewById(R.id.watch2Day3)
button2day3.setOnClickListener(){
makePopupDescription(context, R.drawable.squatgif,
context.getString(R.string.squat_description))
}
as you see, each button’s id differs only two numbers. and for each button I have a certain gif and string to show in popup. So, how can reduce amount of copy-paste in my code?
I thought I can use lists of buttons, gifs and strings. but how to initialise them quickly, not writing every button’s id in constructor?
P.S: sorry for my bad English
2
Answers
o reduce the amount of copy-pasting in your code, you can indeed use lists or arrays to store the button IDs, drawable resource IDs, and string resource IDs. Then you can iterate through these lists to set up the OnClickListener for each button. This approach will make your code more concise and maintainable.
Here’s an example of how you can achieve this in Kotlin:
Create arrays for the button IDs, drawable resource IDs, and string resource IDs.
Iterate through these arrays and set up the OnClickListener for each button.
Here’s the updated code:
// Arrays for button IDs, drawable resource IDs, and string resource IDs
In this example:
buttonIds is an array containing the IDs of the buttons.
drawableIds is an array containing the drawable resource IDs for the GIFs.
stringIds is an array containing the string resource IDs for the descriptions.
The for loop iterates through the indices of the buttonIds array, and for each index, it sets up the OnClickListener for the corresponding button
Yes you can do so, here’s an example :
Then you need to create a loop to do the
setOnClickListener
If you don’t like this option you can create a class
Then you initialize the data according your needs
Then loop through all the exercices