Cha*_*Nan 6 android memory-leaks fragment
我找到了很多方法来避免 android fragment 中的内存泄漏,但哪个是最好的方法?
1.调用onDestroyView时设置view为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!
}
}
Run Code Online (Sandbox Code Playgroud)
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();
}
}
Run Code Online (Sandbox Code Playgroud)
将变量设置为null并不意味着它将被 GC 回收。仅当任何地方都没有其他强引用时,才会对其进行 GC。
设置本身setRetainInstance(true)不会造成Fragment泄漏,它只是保留跨配置更改的实例Fragment。Fragment它可能被认为是“有意识的泄漏”,因为您告诉框架您希望在当前的Activity生命周期之后保留该对象。
现在,如果它不是无 UI 的,Fragment则会泄漏您的信息。发生这种情况是因为UI 将保存对 UI 组件(即 、 等)的引用,并且这些组件保存 的引用。为了避免这种情况,您需要将所有这些引用设置为您正在做的事情。ActivityFragmentFragmentsTextViewsEditTextsViewsActivityContextnull
另外,您可能还需要mLeak从其父级中删除。
| 归档时间: |
|
| 查看次数: |
8805 次 |
| 最近记录: |