package com.example.firstapp.adapter
|
|
import android.view.LayoutInflater
|
import android.view.ViewGroup
|
import androidx.recyclerview.widget.DiffUtil
|
import androidx.recyclerview.widget.ListAdapter
|
import androidx.recyclerview.widget.RecyclerView
|
import com.example.firstapp.R
|
import com.example.firstapp.database.entity.ReminderRecord
|
import com.example.firstapp.databinding.ItemReminderRecordBinding
|
import java.text.SimpleDateFormat
|
import java.util.*
|
|
class ReminderRecordAdapter(
|
private val onItemClick: (ReminderRecord) -> Unit
|
) : ListAdapter<ReminderRecord, ReminderRecordAdapter.ViewHolder>(ReminderRecordDiffCallback()) {
|
|
private val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault())
|
|
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
|
val binding = ItemReminderRecordBinding.inflate(
|
LayoutInflater.from(parent.context),
|
parent,
|
false
|
)
|
return ViewHolder(binding)
|
}
|
|
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
|
holder.bind(getItem(position))
|
}
|
|
inner class ViewHolder(
|
private val binding: ItemReminderRecordBinding
|
) : RecyclerView.ViewHolder(binding.root) {
|
|
init {
|
binding.root.setOnClickListener {
|
val position = bindingAdapterPosition
|
if (position != RecyclerView.NO_POSITION) {
|
onItemClick(getItem(position))
|
}
|
}
|
}
|
|
fun bind(record: ReminderRecord) {
|
binding.apply {
|
categoryNameText.text = record.categoryName
|
contentText.text = record.content
|
timeText.text = dateFormat.format(Date(record.createdAt))
|
|
// 设置状态图标
|
statusIcon.setImageResource(
|
if (record.status == ReminderRecord.STATUS_UNREAD)
|
R.drawable.ic_reminder
|
else
|
R.drawable.ic_add
|
)
|
}
|
}
|
}
|
|
private class ReminderRecordDiffCallback : DiffUtil.ItemCallback<ReminderRecord>() {
|
override fun areItemsTheSame(oldItem: ReminderRecord, newItem: ReminderRecord): Boolean {
|
return oldItem.id == newItem.id
|
}
|
|
override fun areContentsTheSame(oldItem: ReminderRecord, newItem: ReminderRecord): Boolean {
|
return oldItem == newItem
|
}
|
}
|
}
|