As shown in the figure, when the two buttons below are clicked, REPALCEThere are two Fragmnets above, and a memory leak occurs when switching repeatedly
This is the code of Fragment:
public class Fragment2 extends Fragment {
private List<Bitmap> lb = new ArrayList<>();
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
allocBitMap();
allocBitMap();
return inflater.inflate(R.layout.f2, container, false);
}
private void allocBitMap() {
Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.men);
lb.add(b);
}
@Override
public void onDestroy() {
Log.e("onDestroy", "yes, onDestroy");
super.onDestroy();
}
}
This is part of the activity code
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bt_left:
transFragleft();
break;
case R.id.bt_right:
transFragright();
break;
}
}
Fragment f1 = new Fragment1();
Fragment f2 = new Fragment2();
private void transFragleft(){
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.rl_f, f1);
ft.commit();
}
private void transFragright(){
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.rl_f, f2);
ft.commit();
}
This is the memory status when switching repeatedly:
This is LOGCAT. You can see that onDestroy is executed and the entire Fragment life cycle ends immediately
04-27 09:46:04.682 29320-29320/com.sg.fragmentpitfall E/onDestroy: yes, onDestroy
04-27 09:46:06.344 29320-29320/com.sg.fragmentpitfall E/onDestroy: yes, onDestroy
04-27 09:46:07.895 29320-29320/com.sg.fragmentpitfall E/onDestroy: yes, onDestroy
So why is the memory he occupied still there?
Question 2:
How to allocate a certain amount of memory in JAVA for experiments? My bitmap method is too low, and there is CONTEXT in it;
Question 3:
Should we avoid using FRAGMENT (I know that using HIDE/SHOW is better than REPLACE
Thanks!
世界只因有你2017-05-16 13:34:31
Integrate LeakCanary into the code to see what causes the memory leak.
And if the memory graph rises, it does not necessarily mean a memory leak. Every time you apply for a Bitmap, it may not meet the GC standards, so it’s no problem if the memory keeps increasing.