[英]How can I destroy the tablayout fragments at the back event?
I have implemented a tableyout within a fragment, the logic is simple, when I click on an item in a list it derives to a fragment (tableyout), the problem happens when I go back and select another item it shows me the tableyout but with blank views, reviewing a behavior the fragments of the tablayout are never destroyed.我已经在片段中实现了一个 tableyout,逻辑很简单,当我单击列表中的一个项目时,它派生为一个片段(tableyout),当我返回 go 和 select 另一个项目时会出现问题,它向我显示了 tableyout 但有空白视图,查看行为,tablayout 的片段永远不会被破坏。 Here is the adapter code and the main fragment.这是适配器代码和主要片段。 Thanks in advance.提前致谢。
class TabAdapter(fm: FragmentManager): FragmentPagerAdapter(fm) {
override fun getItem(position: Int): Fragment {
return when(position){
0->FormPartOne()
1->FormPartTwo()
2->FormPartThree()
else->FormPartOne()
}
}
override fun getCount(): Int {
return 3
}
override fun getPageTitle(position: Int): CharSequence? {
return when(position){
0->"1"
1->"2"
2->"3"
else->""
}
}
}
Main Fragment:主要片段:
class ReceptionFormFragment : Fragment() {
private lateinit var receptionOrderViewModel: ReceptionOrderViewModel
private lateinit var tabs: TabLayout
private lateinit var viewPager: ViewPager
private lateinit var sectionsPagerAdapter: TabAdapter
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val root = inflater.inflate(R.layout.fragment_reception_form, container, false)
sectionsPagerAdapter = fragmentManager?.let { TabAdapter(it) }!!
viewPager = root.findViewById(R.id.view_pager)
viewPager.adapter = sectionsPagerAdapter
tabs = root.findViewById(R.id.tabs)
tabs.setupWithViewPager(viewPager)
return root
}
}
Replace代替
sectionsPagerAdapter = fragmentManager?.let { TabAdapter(it) }!!
With和
sectionsPagerAdapter = TabAdapter(childFragmentManager)
And it will both work correctly and remove the fragments automatically on back (when this Fragment is removed).它既能正常工作,又能自动移除背面的碎片(当这个 Fragment 被移除时)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.