In the book, which I have, this is chapter 15 “The App Bar”. In the text ‘onCreateOptionsMenu’ is used to select a menu item. However, in Android Studio Dolphin | 2021.3.1 Patch 1 this is declared as deprecated. So I searched and found the solution on Stackoverflow (android - 'setHasOptionsMenu(Boolean): Unit' is deprecated. Deprecated in Java - Stack Overflow). The solution I selected and which works is the following in CrimeListFragment:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val menuHost: MenuHost = requireActivity())
menuHost.addMenuProvider(object : MenuProvider {
override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
// Add menu items here
menuInflater.inflate(R.menu.fragment_crime_list, menu)
}
/**
* Responding to the user selecting an item in the menu, in this case
* adding a new crime. Several menu items can be added here.
*/
override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
// Handle the menu selection
return when (menuItem.itemId) {
R.id.new_crime -> {
showNewCrime()
true
}
else -> false
}
}
})
}
/**
* Function shows to user, which data to add to get a new crime added
* to the database.
*/
private fun showNewCrime() {
viewLifecycleOwner.lifecycleScope.launch {
val newCrime = Crime(
id = UUID.randomUUID(),
title = "",
date = Date(),
isSolved = false
)
crimeListViewModel.addCrime(newCrime)
findNavController().navigate(
CrimeListFragmentDirections.showCrimeDetail(newCrime.id)
)
}
}