You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin中选中ArrayList内所有CheckBox?批量选/取消有无更简洁实现?

Handling Batch Check/Uncheck for ArrayList in Kotlin

Hey there! Let's break down your questions about managing CheckBoxes in an ArrayList with Kotlin:

1. How to check all CheckBoxes in the ArrayList?

It’s straightforward—similar to how you’re unchecking them, just set isChecked to true instead of false:

val checkBoxList: ArrayList<CheckBox> = arrayListOf(/* your CheckBox instances */)
checkBoxList.forEach { it.isChecked = true }

This iterates over every CheckBox in the list and toggles its checked state to true.

2. Is there a more concise way than al.forEach { it.isChecked = false } for batch uncheck?

Your current approach is already clean and idiomatic Kotlin—forEach is the standard, readable way to iterate over collections and perform actions on elements. That said, if you find yourself needing this batch toggle logic multiple times, you can make it even more semantic by creating an extension function:

// Define this extension function in a utils file or anywhere accessible
fun ArrayList<CheckBox>.setAllChecked(checked: Boolean) {
    forEach { it.isChecked = checked }
}

// Use it like this:
checkBoxList.setAllChecked(false) // Uncheck all
checkBoxList.setAllChecked(true)  // Check all

This wraps the repetitive logic into a self-documenting function that makes your code easier to maintain. If you only need to perform this action once or twice, sticking with the direct forEach call is totally fine—no need to over-engineer it.

One minor alternative: Kotlin’s onEach function works similarly but returns the original collection, which is useful if you want to chain operations. For example:

checkBoxList.onEach { it.isChecked = false }.forEach { /* Do something else with each CheckBox */ }

But for just setting the checked state, forEach is slightly more direct since we don’t need the returned collection.


内容的提问来源于stack exchange,提问作者musclebananas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 07:46:24