Leak Canary detects memory leaks for TabLayout with ViewPager2

后端 未结 4 1333
遇见更好的自我
遇见更好的自我 2020-12-18 00:35

I followed the official documentation to setup a TabLayout with ViewPager2. I used the TabLayoutMediator this way to connect the TabLayout with the ViewPager2:



        
相关标签:
4条回答
  • 2020-12-18 00:46

    Your mContext, being exposed by RouteActivity is lingering around even after RouteActivity is destroyed (or recreated). This is happening probably because something is using it. Track what is using mContext and stop that.

    0 讨论(0)
  • 2020-12-18 00:53

    I think this is a bug, its listed on google.

    https://issuetracker.google.com/issues/151212195 https://issuetracker.google.com/issues/154751401

    There is a solution mentioned in the comments that seems to be working for me. Make your FragmentStateAdapter user the constructor

     public FragmentStateAdapter(@NonNull FragmentManager fragmentManager,
                @NonNull Lifecycle lifecycle) {
    

    From your container fragment create the adapter as follows:

    FragmentManager fm = getChildFragmentManager();
    Lifecycle lifecycle = getViewLifecycleOwner().getLifecycle();
    fragmentAdapter = new FragmentAdapter(fm, lifecycle);
    
    0 讨论(0)
  • 2020-12-18 00:53

    I had the same similar problem, you need to set the viewPager adapter to null inside onDestroyView , then possible if you are using databinding make sure u set the binding to null. Goodluck

    0 讨论(0)
  • 2020-12-18 00:55

    You need to detach and set mediator to null in onDestroyView:

    class YourFragment: Fragment() {
        
        private var mediator: TabLayoutMediator? = null
    
        override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
            super.onViewCreated(view, savedInstanceState)
            mediator = TabLayoutMediator(binding.tabLayout, binding.viewPager) { tab, position ->
                tab.setIcon(getTabIcon(position))
                tab.text = getTabTitle(position)
            }
            mediator.attach()
        }
    
        override fun onDestroyView() {
            super.onDestroyView()
            mediator?.detach()
            mediator = null
            binding.viewpager.adapter = null
            _binding = null
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题