I found many way to avoid memory leaks in android fragment, which is the best way?
1.Set the view to null when onDestroyView is called
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.Set all the child view = null and remove the view
@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();
}
}