Skip to content

Instantly share code, notes, and snippets.

@SamueldaCostaAraujoNunes
Created July 30, 2021 15:34
Show Gist options
  • Save SamueldaCostaAraujoNunes/ac37fcc6a76c9bfe57cfd26eb5848023 to your computer and use it in GitHub Desktop.
Save SamueldaCostaAraujoNunes/ac37fcc6a76c9bfe57cfd26eb5848023 to your computer and use it in GitHub Desktop.
package br.com.samuelnunes.rickandmortyapp.ui.characters
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import br.com.samuelnunes.rickandmortyapp.databinding.ItemCharacterBinding
import br.com.samuelnunes.rickandmortyapp.data.entities.Character
/**
* @author Samuel da Costa Araujo Nunes
* Created 30/07/2021 at 12:01
*/
class CharacterAdapter :
ListAdapter<Character, CharacterAdapter.CharacterViewHolder>(CharacterAdapter) {
private companion object : DiffUtil.ItemCallback<Character>() {
override fun areItemsTheSame(oldItem: Character, newItem: Character): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: Character, newItem: Character): Boolean {
return oldItem == newItem
}
}
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): CharacterViewHolder {
val binding = CharacterViewHolder.create(parent)
return CharacterViewHolder(binding)
}
override fun onBindViewHolder(
holder: CharacterViewHolder,
position: Int
) {
val item = getItem(position)
holder.bind(item)
}
class CharacterViewHolder(private val binding: ItemCharacterBinding) :
RecyclerView.ViewHolder(binding.root) {
companion object {
fun create(parent: ViewGroup): ItemCharacterBinding =
ItemCharacterBinding.inflate(LayoutInflater.from(parent.context), parent, false)
}
fun bind(item: Character) {
binding.name.text = item.name
binding.species.text = item.species
binding.status.text = item.status
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment