简体   繁体   中英

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. 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM