[英]How to correctly inflate menus for an action bar from viewpager fragments
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. actionar 是主活动布局中的工具栏,如果每个片段都有一个工具栏并且不添加到主活动中会更容易。 But it looks bad to change fragment with everything and toolbar.
但是用一切和工具栏来改变片段看起来很糟糕。
I just move我只是移动
setHasOptiondMenu(true)
To onResume method到 onResume 方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.