Puzzle: Fragment stack pop cause issue on toolbar

Using fragment, with toolbar is so commonly done these days, and I don’t expect to find any issue with it, until this week. I faced this seemingly weird issue and uncovering the cause of it took me about 2 days. Sharing this so you could learn about it early if you ever see such behavior.

Also I have a related puzzle below for you to solve 😉.

Background

I have an app, with a layout container in the activity. The container took up the entire width of the activity, and it is inflated with fragment or fragments.

Toolbar setup in each fragment

In my app, each of the fragment would have their respective toolbar with it’s menu. As there’s no common toolbar, it is set in the fragment instead of the activity. The code as below

(activity as AppCompatActivity).setSupportActionBar(toolbar)

In all my toolbar, I have menu that enable one to click and

override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
activity?.onBackPressed()
return…

--

--