gpt4 book ai didi

Android DataBinding 正在泄漏内存

转载 作者:行者123 更新时间:2023-12-01 03:06:02 32 4
gpt4 key购买 nike

我正在使用数据绑定(bind)并且我已经声明了 lateinit var对于绑定(bind)以及当我要去不同的 fragment Leaky canary 显示泄漏时。

fragment

class HomeFragment : BottomNavViewHostBaseFragment() {

private lateinit var viewModel: HomeViewModel
private lateinit var binding: FragmentHomeBinding

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
viewModel = ViewModelProviders.of(this).get(HomeViewModel::class.java)
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_home, container, false)
binding.lifecycleOwner = viewLifecycleOwner
binding.viewModel = viewModel
return binding.root
}

...
}

这是来自 Leaky Carny 的信息
androidx.constraintlayout.widget.ConstraintLayout has leaked:
Toast$TN.mNextView
↳ LinearLayout.mContext
↳ MainActivity.navigationView
↳ NavigationView.listener
↳ BaseFragment$setNavigationDrawerItemSelectedListener$1.this$0 (anonymous implementation of com.google.android.material.navigation.NavigationView$OnNavigationItemSelectedListener) ↳ OrdersHostFragment.mFragmentManager
↳ FragmentManagerImpl.mActive
↳ HashMap.table
↳ array HashMap$HashMapEntry[].[0]
↳ HashMap$HashMapEntry.value
↳ HomeFragment.!(binding)!
↳ FragmentHomeBindingImpl.!(mboundView0)!
↳ ConstraintLayout

我该如何解决这个问题,我需要做什么 binding=null里面 onDestroyView ?但是,如果我需要这样做,那么 binding.lifecycleOwner = viewLifecycleOwner 的意义何在?然后?

最佳答案

这是来自 google docs 的推荐方式初始化和清除 Fragments 中的绑定(bind):

Kotlin :

private var _binding: ResultProfileBinding? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!

override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = ResultProfileBinding.inflate(inflater, container, false)
val view = binding.root
return view
}

override fun onDestroyView() {
super.onDestroyView()
_binding = null
}

java :
private ResultProfileBinding binding;

@Override
public View onCreateView (LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
binding = ResultProfileBinding.inflate(inflater, container, false);
View view = binding.getRoot();
return view;
}

@Override
public void onDestroyView() {
super.onDestroyView();
binding = null;
}

另外,这里是 medium blog post阅读以摆脱与 Property Delegate 的绑定(bind)内存泄漏。

关于Android DataBinding 正在泄漏内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57647751/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com