Rahul Chowdhury 🕶
Posted on August 1, 2019
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?
💖 💪 🙅 🚩
Rahul Chowdhury 🕶
Posted on August 1, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
android Quick example of creating a custom Kotlin coroutine and scoping it to a Android service.
November 21, 2024