如何在 Kotlin 中通过 CheckBox 和 RecyclerView 使用 SparseBooleanArray [英] How to use SparseBooleanArray in Kotlin with CheckBox and RecyclerView
问题描述
我发现在滚动 Recyclerview 时,它丢失了复选框状态.您可以使用 SparseBooleanArray 来存储整数、布尔值.我在网上找到了 Java 的代码.但是如何在 Kotlin 中做到这一点呢?为什么是 SparseBooleanArray,HashMap 有什么问题?
I have found while scrolling Recyclerview, it lost checkboxes states. You can use SparseBooleanArray for storing Integer, Boolean values. I found code for Java on the web. But how to do that in Kotlin? Why SparseBooleanArray, what's wrong with HashMap?
推荐答案
SparseArray
可用于在键为原始类型时替换 HashMap
.不同的键/值类型有一些变体,尽管并非所有变体都是公开可用的.
SparseArray
can be used to replace HashMap
when the key is a primitive type. There are some variants for different key/value types, even though not all of them are publicly available.
好处是:
- 无需分配
- 没有拳击
使用 HashMap 可以正常工作 - 但是使用 SparseArray 类型之一可能会稍微提高性能.
Working with a HashMap would work just fine - however it can be slightly more performant to use one of the SparseArray types instead.
为了在 Kotlin 中使用 SparseBooleanArray,您可以像在 Java 中一样使用它:
In order to use SparseBooleanArray in Kotlin, you can use it just like you would from Java:
val key = 1
val map = SparseBooleanArray()
map.put(key, true)
val value = map.get(key)
如果您导入 ktx 扩展,您可以使用 Kotlin 风格的访问器,如下所示:
If you import the ktx extensions, you can use the Kotlin-style accessors like the following:
map[key] = true
val value = map[key]
这篇关于如何在 Kotlin 中通过 CheckBox 和 RecyclerView 使用 SparseBooleanArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!