如图,当点击下面的两个按钮时,REPALCE上面的Fragmnet,共两个,反复切换时发生了内存泄漏
这是Fragment的代码:
public class Fragment2 extends Fragment {
private List 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();
}
}
这是Activity的部分代码
@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();
}
这是反复切换时的内存状态:
这是LOGCAT,可以看到onDestroy执行了,整个Fragment生命周期马上就结束了
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
那么为什么他占用的那块内存还在呢?
提问2:
JAVA中怎样分配一定内存,用于实验,我这种bitmap的方法太LOW了,而且里面还有CONTEXT;
提问3:
是否应该避免使用FRAGMENT(我知道用HIDE/SHOW的方式要比REPLACE要好
谢谢!