package com.example.firstapp.adapter
|
|
import android.view.LayoutInflater
|
import android.view.ViewGroup
|
import androidx.recyclerview.widget.RecyclerView
|
import com.example.firstapp.databinding.ItemCategorySelectorBinding
|
import com.example.firstapp.model.CategoryConfig
|
import java.util.Collections
|
|
/**
|
* Adapter for the category selector recycler view.分类选择的适配器
|
*/
|
class CategorySelectorAdapter : RecyclerView.Adapter<CategorySelectorAdapter.ViewHolder>() {
|
|
private var categories = mutableListOf<CategoryConfig>()
|
private var lastCheckedPosition = -1 // 记录最后一个选中的位置
|
|
class ViewHolder(val binding: ItemCategorySelectorBinding) : RecyclerView.ViewHolder(binding.root)
|
|
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
|
val binding = ItemCategorySelectorBinding.inflate(
|
LayoutInflater.from(parent.context), parent, false
|
)
|
return ViewHolder(binding)
|
}
|
|
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
|
val category = categories[position]
|
holder.binding.apply {
|
categoryName.text = category.name
|
categoryCheckBox.isChecked = category.isEnabled
|
|
// 如果只有一个选中的项,禁用其复选框
|
categoryCheckBox.isEnabled = !(getEnabledCount() == 1 && category.isEnabled)
|
|
categoryCheckBox.setOnCheckedChangeListener { _, isChecked ->
|
if (isChecked || getEnabledCount() > 1) {
|
categories[position] = category.copy(isEnabled = isChecked)
|
notifyDataSetChanged() // 刷新所有项以更新禁用状态
|
} else {
|
// 如果要取消选中且只有一个选中项,恢复选中状态
|
categoryCheckBox.isChecked = true
|
}
|
}
|
}
|
}
|
|
private fun getEnabledCount(): Int {
|
return categories.count { it.isEnabled }
|
}
|
|
override fun getItemCount() = categories.size
|
|
fun moveItem(fromPosition: Int, toPosition: Int) {
|
Collections.swap(categories, fromPosition, toPosition)
|
notifyItemMoved(fromPosition, toPosition)
|
}
|
|
fun setCategories(newCategories: List<CategoryConfig>) {
|
categories.clear()
|
categories.addAll(newCategories)
|
notifyDataSetChanged()
|
}
|
|
fun getCategories() = categories.toList()
|
}
|