'onOptionsItemSelected is not called for `android.R.id.home`
I looked trough all already existing threads, but I was unable to figure out why my onOptionsItemSelected method in Fragment is not called for Up/Home button click in App Toolbar (android.R.id.home).
class SomeFragment : Fragment() {
override fun onCreateView(//...): View {
//...
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setHasOptionsMenu(true)
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
menu.add(Menu.NONE, 1, Menu.NONE, "Test").setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
1 -> {
// This does get called normally for right placed "Test" button
}
else -> {
// Nothing gets called here when I click left placed back button
}
}
return true
}
}
I have setDisplayHomeAsUpEnabled(true) in my BaseActivityHandler and back button works, I am just unable to catch it in fragment (I need to show alert "Are you sure?")
EDIT: I found out that in Activity, onOptionsItemSelected is handling android.R.id.home and I am doing navController.navigateUp() in there. How to make Fragment's onOptionsItemSelected called first, so I can first of all show the alert and then do navController.navigateUp()?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
