Assume different menuicons are to be displayed on the toolbar of a tabbed activity at different tabs.
One solution is to build a distinct menu for each fragment/tab and inflate at the corresponding onCreateOptionsMenu()
function. However, this solution is proven to be slow and lagging. Menuicons does not disappear fast enough.
The second solution is to inflate all menuicons in the "activity" and then hide when necessary. This option is faster.
I tried pageChangeListener
and tabSelectedListener
. But somehow menuicons did not disapear at first click. They disappear after both hiding tabs are clicked in row. If invalidateOptionsMenu()
used, menuicons are NOT hidden at all.
Do you have an idea why this happens? Or do you have another fast method to hide the icons?
Here is the related code:
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
Log.v("MainAct", "MainAct onCreateOptionsMenu")
menuInflater.inflate(R.menu.mainmenu, menu)
viewPager.addOnPageChangeListener(object : ViewPager.SimpleOnPageChangeListener() {
override fun onPageSelected(position: Int) {
when (position) {
0 -> {
menu!!.findItem(R.id.menuicon_contacts).isVisible = false
menu.findItem(R.id.menuicon_add).isVisible = false
invalidateOptionsMenu() // With this line menuicons does not disappear at all
}
1 -> {
menu!!.findItem(R.id.menuicon_contacts).isVisible = false
menu.findItem(R.id.menuicon_add).isVisible = false
invalidateOptionsMenu()
}
2 -> {
menu!!.findItem(R.id.menuicon_contacts).isVisible = true
menu.findItem(R.id.menuicon_add).isVisible = true
invalidateOptionsMenu()
}
}
}
})
return super.onCreateOptionsMenu(menu)
}