DEV Community

Rahul Chowdhury 🕶
Rahul Chowdhury 🕶

Posted on

Day 9: Display list of elephants

I finally added a RecyclerView to display the list of elephants on the home fragment which is ElephantListFragment.

With a mocktail of ListAdapter, Data Binding and DiffUtil, populating data to the RecyclerView in an efficient way was damn easy.

Here's my sleek adapter:

class ElephantListAdapter : ListAdapter<Elephant, ElephantListAdapter.ViewHolder>(ElephantDiffCallback()) {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val binding = ElephantListItemBinding.inflate(
            LayoutInflater.from(parent.context),
            parent,
            false
        )

        return ViewHolder(binding)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val elephant = getItem(position)
        holder.bind(elephant, createClickListener(elephantName = elephant.name))
    }

    class ViewHolder(
        private val elephantListItemBinding: ElephantListItemBinding
    ) : RecyclerView.ViewHolder(elephantListItemBinding.root) {

        fun bind(item: Elephant, listener: View.OnClickListener) {
            elephantListItemBinding.apply {
                elephant = item
                clickListener = listener
                executePendingBindings()
            }
        }
    }

    private fun createClickListener(elephantName: String): View.OnClickListener {
        return View.OnClickListener {
            val navArgs = Bundle()
            navArgs.putString("elephantName", elephantName)

            it.findNavController().navigate(R.id.elephantProfileFragment, navArgs)
        }
    }
}

private class ElephantDiffCallback : DiffUtil.ItemCallback<Elephant>() {
    override fun areItemsTheSame(oldItem: Elephant, newItem: Elephant): Boolean =
        oldItem.id == newItem.id

    override fun areContentsTheSame(oldItem: Elephant, newItem: Elephant): Boolean =
        oldItem == newItem
}

Polishes can be done here and there which I'll do in some time.

Check out the repo, here: https://github.com/rahulchowdhury/elly

Next, I would like to target UI testing with Espresso. Any handy guide for me?

Top comments (0)