[英]How to set action for other item not selected in a Recyclerview
我正在使用回收器視圖適配器庫來顯示帶有回收器視圖的列表。 我還有一個復選框要顯示。 我想要的是一次選擇復選框。 一旦我選擇了一個復選框,任何以前選擇的復選框都應該被取消選中。
https://github.com/utsmannn/Recycling
val genderList = resources.getStringArray(R.array.gender_list).toList()
gender_rv.setupAdapter<String>(R.layout.specialty_layout_item){adapter, context, list ->
bind { itemView, position, item ->
itemView.specialty_item_checkbox.show()
itemView.specialty_item_checkbox.text = item
if (itemView.specialty_item_checkbox.isChecked){
genderValue += itemView.specialty_item_checkbox.text.toString().toLowerCase()
}
}
setLayoutManager(LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, true))
submitList(genderList)
}
我在我的一個項目中所做的是:
fun bind(item: Item, onItemToggled: (Item) -> Unit) {
itemView.checkbox.setOnCheckedChangeListener(null)
itemView.checkbox.isChecked = item.selected
itemView.checkbox.setOnCheckedChangeListener { compoundButton, b ->
onItemToggled(item.copy(selected = !item.selected))
}
}
如果您只想檢查一項,我會映射列表以確保只選擇一項:
data class RecyclerItem(val text: String, val selected: Boolean = false)
var genderList = resources.getStringArray(R.array.gender_list).toList().map {
RecyclerItem(text = it)
}
gender_rv.setupAdapter<String>(R.layout.specialty_layout_item){adapter, context, list ->
bind { itemView, position, item ->
itemView.specialty_item_checkbox.show()
itemView.specialty_item_checkbox.text = item.text
itemView.specialty_item_checkbox.setOnCheckedChangeListener(null)
itemView.specialty_item_checkbox.isChecked = item.selected
itemView.checkbox.specialty_item_checkbox { compoundButton, b ->
genderList = genderList.map {
if(it == item) {
it.copy(selected = !item.selected)
} else {
it.copy(selected = false)
}
adapter.submitList(genderList)
}
}
我能夠使用以下方法處理它。
var genderList = resources.getStringArray(R.array.gender_list).toList().map {
RecyclerItem(text = it)
}
val checkboxes = arrayListOf<CheckBox>()
gender_rv.setupAdapter<RecyclerItem>(R.layout.specialty_layout_item) { adapter, context, list ->
bind { itemView, position, item ->
itemView.specialty_item_checkbox.show()
itemView.specialty_item_checkbox.text = item?.text
itemView.specialty_item_checkbox.isChecked = item?.selected!!
checkboxes.add(itemView.specialty_item_checkbox)
itemView.specialty_item_checkbox.setOnCheckedChangeListener { compoundButton, b ->
if (b) {
compoundButton.isChecked = true
val otherCheckboxes =
checkboxes.filter { checkBox -> checkBox.text != compoundButton.text }
otherCheckboxes.forEach { checkbox ->
if (checkbox.isChecked) {
checkbox.isChecked = !checkbox.isChecked
} else {
}
}
val sz = otherCheckboxes.size
Log.i("checkbox", "hello ${compoundButton.text} othersSize $sz")
}
}
}
setLayoutManager(
LinearLayoutManager(
requireContext(),
LinearLayoutManager.HORIZONTAL,
false
)
)
submitList(genderList)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.