e-ntfy-android/app/src/main/java/io/heckel/ntfy/ui/DetailAdapter.kt

67 lines
2.8 KiB
Kotlin
Raw Normal View History

2021-10-31 20:19:25 +01:00
package io.heckel.ntfy.ui
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import io.heckel.ntfy.R
import io.heckel.ntfy.data.Notification
import java.util.*
2021-11-03 18:56:08 +01:00
class DetailAdapter(private val onClick: (Notification) -> Unit, private val onLongClick: (Notification) -> Unit) :
2021-10-31 20:19:25 +01:00
ListAdapter<Notification, DetailAdapter.DetailViewHolder>(TopicDiffCallback) {
2021-11-03 18:56:08 +01:00
val selected = mutableSetOf<String>() // Notification IDs
2021-10-31 20:19:25 +01:00
/* Creates and inflates view and return TopicViewHolder. */
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DetailViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.detail_fragment_item, parent, false)
2021-11-03 18:56:08 +01:00
return DetailViewHolder(view, selected, onClick, onLongClick)
2021-10-31 20:19:25 +01:00
}
/* Gets current topic and uses it to bind view. */
override fun onBindViewHolder(holder: DetailViewHolder, position: Int) {
holder.bind(getItem(position))
}
2021-11-03 18:56:08 +01:00
fun toggleSelection(notificationId: String) {
if (selected.contains(notificationId)) {
selected.remove(notificationId)
} else {
selected.add(notificationId)
}
}
2021-10-31 20:19:25 +01:00
/* ViewHolder for Topic, takes in the inflated view and the onClick behavior. */
2021-11-03 18:56:08 +01:00
class DetailViewHolder(itemView: View, private val selected: Set<String>, val onClick: (Notification) -> Unit, val onLongClick: (Notification) -> Unit) :
2021-10-31 20:19:25 +01:00
RecyclerView.ViewHolder(itemView) {
private var notification: Notification? = null
private val dateView: TextView = itemView.findViewById(R.id.detail_item_date_text)
private val messageView: TextView = itemView.findViewById(R.id.detail_item_message_text)
fun bind(notification: Notification) {
this.notification = notification
dateView.text = Date(notification.timestamp * 1000).toString()
messageView.text = notification.message
itemView.setOnClickListener { onClick(notification) }
2021-11-03 18:56:08 +01:00
itemView.setOnLongClickListener { onLongClick(notification); true }
if (selected.contains(notification.id)) {
itemView.setBackgroundResource(R.color.primarySelectedRowColor);
}
2021-10-31 20:19:25 +01:00
}
}
object TopicDiffCallback : DiffUtil.ItemCallback<Notification>() {
override fun areItemsTheSame(oldItem: Notification, newItem: Notification): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: Notification, newItem: Notification): Boolean {
return oldItem == newItem
}
}
}