I have my viewpager as follows:
val pagerAdapter = ViewPagerAdapter()
viewPager2.apply { offscreenPageLimit = 2; adapter = pagerAdapter }
override fun createFragment(position: Int): Fragment = list[position].fragment
So all fragments are inflated from the start.
But I don't know how or where to inflate the menu for my action bar from each fragment. Because if I inflate it like this:
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentGenericBinding.inflate(inflater, container, false)
setHasOptionsMenu(true)
return bind.root
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.menu_add, menu)
super.onCreateOptionsMenu(menu, inflater)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.menu_add -> FragmentAddMenu().show(parentFragmentManager, "Add Menu")
}
return super.onOptionsItemSelected(item)
}
override fun onResume() {
super.onResume()
(requireActivity() as AppCompatActivity).supportActionBar?.title = "Menú"
}
The actionbar menu and title in the first tablayout snippet is from the last inflated fragment.
If I switch between fragments they inflate correctly. But it only happens at the start of the application with the first fragment.
I would like to be able to inflate each menu once the fragment is r,esumed but I couldn't find any examples on the internet or any way around the problem. And if I don't clean the menu on each inflation, the buttons accumulate.
The actionar is a toolbar in the layout of the main activity, it would be easier if each fragment had a toolbar and not added to the main activity. But it looks bad to change fragment with everything and toolbar.
CodePudding user response:
I just move
setHasOptiondMenu(true)
To onResume method