我是 Android 开发新手。我正在编写包含训练练习的健身应用程序页面。我有很多按钮,点击我想显示包含一些与每个按钮不同的内容的弹出窗口。我有这个代码:
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))
}
如您所见,每个按钮的 id 只有两个数字不同。对于每个按钮,我都有一个特定的 gif 和字符串要在弹出窗口中显示。 那么,如何减少代码中的复制粘贴量呢? 我想我可以使用按钮、gif 和字符串列表。但如何快速初始化它们,而不是在构造函数中写入每个按钮的 id?
PS:抱歉我的英语不好
为了减少代码中的复制粘贴量,您确实可以使用列表或数组来存储按钮 ID、可绘制资源 ID 和字符串资源 ID。然后您可以迭代这些列表来为每个按钮设置 OnClickListener。这种方法将使您的代码更加简洁和可维护。
以下是如何在 Kotlin 中实现此目的的示例:
为按钮 ID、可绘制资源 ID 和字符串资源 ID 创建数组。 遍历这些数组并为每个按钮设置 OnClickListener。 这是更新后的代码:
// 按钮 ID、可绘制资源 ID 和字符串资源 ID 的数组
val buttonIds = arrayOf(R.id.watch4day2, R.id.watch5Day2, R.id.watch1Day3, R.id.watch2Day3)
val drawableIds = arrayOf(R.drawable.pullupsgif, R.drawable.triceps_press, R.drawable.warmupgif, R.drawable.squatgif)
val stringIds = arrayOf(R.string.pullups_description, R.string.triceps_press_description, R.string.warmup_description, R.string.squat_description)
// Iterate through the arrays and set up the OnClickListener for each button
for (i in buttonIds.indices) {
val button: Button = view.findViewById(buttonIds[i])
button.setOnClickListener {
makePopupDescription(context, drawableIds[i], context.getString(stringIds[i]))
}
}
在此示例中:
buttonIds 是一个包含按钮 ID 的数组。 drawableIds 是一个包含 GIF 的可绘制资源 ID 的数组。 stringIds 是一个包含描述的字符串资源 ID 的数组。 for循环遍历buttonIds数组的索引,对于每个索引,它为相应的按钮设置OnClickListener
我想我可以使用按钮、GIF 和字符串列表。
是的,你可以这样做,这是一个例子:
//Buttons array
val buttonIds = arrayOf(
R.id.watch4day2, R.id.watch5Day2, R.id.watch1Day3, R.id.watch2Day3
)
//Gifs array
val drawableResources = arrayOf(
R.drawable.pullupsgif, R.drawable.triceps_press, R.drawable.warmupgif, R.drawable.squatgif
)
//StringResources array
val stringResources = arrayOf(
R.string.pullups_description, R.string.triceps_press_description, R.string.warmup_description, R.string.squat_description
)
然后你需要创建一个循环来执行
setOnClickListener
for (i in buttonIds.indices) {
val button: Button = view.findViewById(buttonIds[i])
button.setOnClickListener {
makePopupDescription(
context,
drawableResources[i],
context.getString(stringResources[i])
)
}
}