zhujie
2025-04-03 fe04012057d024770e0180543483d393281a542f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
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()