Adding Items Interactively
We have just learned how to remove items interactively. What about adding new items? Let's look into it.
Similar to the way we implemented the removal of items, we start by adding a function to our adapter:
fun addItem(position: Int, item: ListItemUiModel) { listData.add(position, item) notifyItemInserted(position) }
You will notice that the implementation is very similar to the removeItem(Int)
function we implemented earlier. This time, we also receive an item to add and a position to add it. We then add it to our listData
list and notify RecyclerView
that we added an item in the requested position.
To trigger a call to addItem(Int, ListItemUiModel)
, we could add a button to our main activity layout. This button could be as follows:
<Button android:id="@+id/main_add_item_button" android:layout_width="match_parent" ...