2021-10-27 03:44:12 +02:00
|
|
|
package io.heckel.ntfy
|
2021-10-25 15:01:10 +02:00
|
|
|
|
|
|
|
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.data.Topic
|
|
|
|
|
2021-10-25 19:45:56 +02:00
|
|
|
class TopicsAdapter(private val onClick: (Topic) -> Unit) :
|
|
|
|
ListAdapter<Topic, TopicsAdapter.TopicViewHolder>(TopicDiffCallback) {
|
2021-10-25 15:01:10 +02:00
|
|
|
|
2021-10-25 19:45:56 +02:00
|
|
|
/* ViewHolder for Topic, takes in the inflated view and the onClick behavior. */
|
|
|
|
class TopicViewHolder(itemView: View, val onClick: (Topic) -> Unit) :
|
2021-10-25 15:01:10 +02:00
|
|
|
RecyclerView.ViewHolder(itemView) {
|
2021-10-25 19:45:56 +02:00
|
|
|
private val topicTextView: TextView = itemView.findViewById(R.id.topic_text)
|
|
|
|
private var currentTopic: Topic? = null
|
2021-10-25 15:01:10 +02:00
|
|
|
|
|
|
|
init {
|
|
|
|
itemView.setOnClickListener {
|
2021-10-25 19:45:56 +02:00
|
|
|
currentTopic?.let {
|
2021-10-25 15:01:10 +02:00
|
|
|
onClick(it)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-10-25 19:45:56 +02:00
|
|
|
fun bind(topic: Topic) {
|
|
|
|
currentTopic = topic
|
2021-10-27 03:44:12 +02:00
|
|
|
val shortBaseUrl = topic.baseUrl.replace("https://", "") // Leave http:// untouched
|
|
|
|
val shortName = itemView.context.getString(R.string.topic_short_name_format, shortBaseUrl, topic.name)
|
|
|
|
topicTextView.text = shortName
|
2021-10-25 15:01:10 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-10-25 19:45:56 +02:00
|
|
|
/* Creates and inflates view and return TopicViewHolder. */
|
|
|
|
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TopicViewHolder {
|
2021-10-25 15:01:10 +02:00
|
|
|
val view = LayoutInflater.from(parent.context)
|
2021-10-25 19:45:56 +02:00
|
|
|
.inflate(R.layout.topic_item, parent, false)
|
|
|
|
return TopicViewHolder(view, onClick)
|
2021-10-25 15:01:10 +02:00
|
|
|
}
|
|
|
|
|
2021-10-25 19:45:56 +02:00
|
|
|
/* Gets current topic and uses it to bind view. */
|
|
|
|
override fun onBindViewHolder(holder: TopicViewHolder, position: Int) {
|
|
|
|
val topic = getItem(position)
|
|
|
|
holder.bind(topic)
|
2021-10-25 15:01:10 +02:00
|
|
|
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-10-25 19:45:56 +02:00
|
|
|
object TopicDiffCallback : DiffUtil.ItemCallback<Topic>() {
|
2021-10-25 15:01:10 +02:00
|
|
|
override fun areItemsTheSame(oldItem: Topic, newItem: Topic): Boolean {
|
|
|
|
return oldItem == newItem
|
|
|
|
}
|
|
|
|
|
|
|
|
override fun areContentsTheSame(oldItem: Topic, newItem: Topic): Boolean {
|
2021-10-27 03:44:12 +02:00
|
|
|
return oldItem.name == newItem.name
|
2021-10-25 15:01:10 +02:00
|
|
|
}
|
|
|
|
}
|