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

61 lines
2.1 KiB
Kotlin
Raw Normal View History

2021-10-27 03:44:12 +02:00
package io.heckel.ntfy
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 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) :
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
init {
itemView.setOnClickListener {
2021-10-25 19:45:56 +02:00
currentTopic?.let {
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 19:45:56 +02:00
/* Creates and inflates view and return TopicViewHolder. */
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TopicViewHolder {
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 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 19:45:56 +02:00
object TopicDiffCallback : DiffUtil.ItemCallback<Topic>() {
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
}
}