Step #8: Fixing the Delete-on-Add Problem
Right now, when you edit an existing to-do item, the “delete” app bar item appears. It also appears when you are adding a new to-do item. This is unnecessary and may confuse the user. Plus, it may not work all that well, since we cannot delete an item that has not been added.
Fortunately, fixing this requires just one line of code: updating isVisible
on the MenuItem
corresponding to “delete”.
Modify onCreateOptionsMenu()
of EditFragment
to look like:
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.actions_edit, menu)
menu.findItem(R.id.delete).isVisible = args.modelId != null
super.onCreateOptionsMenu(menu, inflater)
}
Here, we retrieve the delete
MenuItem
and call setVisibility()
with true
if we have a model, false
otherwise. This has the desired effect: removing the “delete” item if we do not have anything to delete.
And, if you run the app and go to add a new item, the delete icon does not appear in the app bar, but it will appear if you try to edit an existing item.
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.