我发现很多方法可以避免android片段中的内存泄漏,这是最好的方法吗?
1.调用onDestroyView时将视图设置为null
public class LeakyFragment extends Fragment{
private View mLeak; // retained
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mLeak = inflater.inflate(R.layout.whatever, container, false);
return mLeak;
}
@Override
public void onDestroyView() {
super.onDestroyView();
mLeak = null; // now cleaning up!
}
}
2.设置所有子视图= null并删除视图
@Override
public void onDestroyView(){
super.onDestroyView();
unbindDrawables(mLeak);
}
private void unbindDrawables(View view){
if (view.getBackground() != null){
view.getBackground().setCallback(null);
}
if (view instanceof ViewGroup && !(view instanceof AdapterView)){
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++){
unbindDrawables(((ViewGroup) view).getChildAt(i));
}
((ViewGroup) view).removeAllViews();
}
}
答案 0 :(得分:0)
将变量设置为null
并不意味着它会获得GC&#39; d。如果在任何地方都没有其他强引用,那么它只会是GC。
设置setRetainInstance(true)
本身不会导致Fragment
泄漏,它只会保留配置更改中Fragment
的实例。它可能被视为有意识的泄漏,因为您告诉框架您要保留Fragment
对象超过当前Activity
的生命周期。
如果Fragment
不是无用户界面Activity
,则Fragment
会泄露Fragments
。发生这种情况是因为具有UI的TextViews
将保留对UI组件的引用(即EditTexts
,Views
等),并且这些Activity
包含{{1}的引用} {&#39; s Context
。为了避免这种情况,您需要将所有这些引用设置为null
。
此外,您可能还需要从其父级中删除mLeak
。