Android Option Menu and Tab Layout duplicate the menu when swiping and cancel them

108 Views Asked by At

The problem is the menu icon is duplicated when swiping the tab layout. If the swipe is canceled then the duplicate (not duplicate actually, but the other menu layout that the other fragment has or the destination fragment of the swipe) stays there. But if the swipe is successful, then it wont appear again when swiping or cancelling. It only happens for the first time when the fragment has not been initialized

Here is what it looks like by the menu items duplicate when swiping then cancel1

When swiping is canceled2

When swiping is continued to other tabs3

AND, when I clicked the order fragment from the tab layout (from the machine fragment), it will show 3 duplicate refresh icon (menu items) momentarily and then disappear after the swipe (when state in onPageScrollStateChanged is equal to 0 or idle in other fragment) is settled

After the swiping is continued (or when each fragment in the tablayout is already initiated), the menu wont duplicate anymore when swiping back and forth (or when state = 1 in onPageScrollStateChanged)

I used setHasOptionsMenu() in every fragment that is in the tab layout and each of them inflate the same menu layout

I tried this using interface from the parent fragment but it doesn't work (it ONLY WORKS after successfully swiping to other fragment where the menu icon will disappear when swiping the tab layout, but it doesn't work when the other fragment has never been accessed)

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
   

    setHasOptionsMenu(true)
}

override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
    super.onCreateOptionsMenu(menu, inflater)
    inflater.inflate(R.menu.refresh_menu, menu)
    HomeFragment.setHideRefresButtonOnPageScrolled(object: HomeFragment.HideRefreshButton {
        override fun onSwipe(state: Int) {
            if (state == 1) {
                menu.findItem(R.id.refresh).isVisible = false
                activity?.invalidateOptionsMenu()
            } else if (state == 0){
                menu.findItem(R.id.refresh).isVisible = true
                activity?.invalidateOptionsMenu()
            }
        }
    })
}

how do I fix this? any help is appreciated

1

There are 1 best solutions below

0
lezrytt On

fixed it by calling

menu.clear

before inflating another menu on onCreateOptionsMenu in each fragment in tabs layout