Adding animations in the RecyclerView items: Step 1
To populate our data we're going to need of course an adapter. Since we already have one in place we can just copy paste the same and just remove the listener as we won't need it. We can also change the objects to a list of integers
CounterItem.kt
data class CounterItem(val avatarId: Int)
CounterAdapter.kt
class
(val context: Context, val items: List<Int>) : RecyclerView.Adapter<CounterAdapter.ViewHolder>() {
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val avatar = itemView.iv_added_item
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CounterAdapter.ViewHolder {
return ViewHolder(LayoutInflater.from(context).inflate(R.layout.li_detail, parent, false))
}
override fun getItemCount(): Int {
return items.size
}
override fun onBindViewHolder(holder: CounterAdapter.ViewHolder, position: Int) {
holder.avatar.let { Glide.with(context).load(R.drawable.avatar_1).into(it) }
}
}
We want to add an item to our list when the "add" button is clicked and remove one when the "remove" is clicked till they're all gone. So let's change our click listeners and bind our adapter to the RecyclerView.
class DetailActivity : AppCompatActivity() {
...
private lateinit var list: List<Int>
private lateinit var counterAdapter: CounterAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
...
list = arrayListOf()
counterAdapter = CounterAdapter(this@DetailActivity, list)
rv_added_items.apply {
setHasFixedSize(false)
adapter = counterAdapter
}
...
bt_increase.setOnClickListener {
tv_counter.text = "${++counter}"
(list as ArrayList<Int>).add(counter)
counterAdapter.notifyItemInserted(counter)
counterAdapter.notifyItemRangeChanged(list.size - 1, list.size)
}
bt_decrease.setOnClickListener {
when {
counter > 0 -> {
tv_counter.text = "${--counter}"
// we always remove the last item
(list as ArrayList<Int>).remove(list.size)
counterAdapter.notifyItemRemoved(list.size)
counterAdapter.notifyItemRangeChanged(list.size - 1, list.size)
}
else -> tv_counter.text = "$counter"
}
}
}
companion object {
...
}
}