72 lines
2.3 KiB
Kotlin
72 lines
2.3 KiB
Kotlin
package com.example.defenseapplication.adapter
|
|
|
|
import android.view.LayoutInflater
|
|
import android.view.ViewGroup
|
|
import androidx.core.content.ContextCompat
|
|
import androidx.recyclerview.widget.RecyclerView
|
|
import com.example.defenseapplication.R
|
|
import com.example.defenseapplication.databinding.ItemSwitchFamilyBinding
|
|
import com.example.defenseapplication.model.FamilyItem
|
|
|
|
class FamilySwitchAdapter(
|
|
private var familyList: List<FamilyItem>,
|
|
private val onItemClickListener: (FamilyItem) -> Unit
|
|
) : RecyclerView.Adapter<FamilySwitchAdapter.FamilyViewHolder>() {
|
|
|
|
private var selectedPosition = 0
|
|
|
|
fun updateList(newList: List<FamilyItem>) {
|
|
familyList = newList
|
|
selectedPosition = 0
|
|
notifyDataSetChanged()
|
|
}
|
|
|
|
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FamilyViewHolder {
|
|
val binding = ItemSwitchFamilyBinding.inflate(
|
|
LayoutInflater.from(parent.context),
|
|
parent,
|
|
false
|
|
)
|
|
return FamilyViewHolder(binding)
|
|
}
|
|
|
|
override fun onBindViewHolder(holder: FamilyViewHolder, position: Int) {
|
|
holder.bind(familyList[position], position == selectedPosition)
|
|
}
|
|
|
|
override fun getItemCount(): Int = familyList.size
|
|
|
|
fun selectPosition(position: Int) {
|
|
val previousPosition = selectedPosition
|
|
selectedPosition = position
|
|
notifyItemChanged(previousPosition)
|
|
notifyItemChanged(selectedPosition)
|
|
}
|
|
|
|
fun getSelectedItem(): FamilyItem = familyList[selectedPosition]
|
|
|
|
inner class FamilyViewHolder(
|
|
private val binding: ItemSwitchFamilyBinding
|
|
) : RecyclerView.ViewHolder(binding.root) {
|
|
|
|
fun bind(item: FamilyItem, isSelected: Boolean) {
|
|
binding.tvFamilyName.text = item.name
|
|
|
|
binding.root.setBackgroundColor(
|
|
ContextCompat.getColor(
|
|
binding.root.context,
|
|
if (isSelected) R.color.bg_gray else R.color.white
|
|
)
|
|
)
|
|
|
|
binding.root.setOnClickListener {
|
|
val position = bindingAdapterPosition
|
|
if (position != RecyclerView.NO_POSITION) {
|
|
selectPosition(position)
|
|
onItemClickListener(item)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|