参考:http://www.tuicool.com/articles/3qUFzaN
activity管理fragment的时候有时候出现重叠现象。出现正是因为使用了Fragment的状态保存,当系统内存不足,Fragment的宿主Activity回收的时候,Fragment的实例并没有随之被回收。Activity被系统回收时,会主动调用onSaveInstance()方法来保存视图层(View Hierarchy),所以当Activity通过导航再次被重建时,之前被实例化过的Fragment依然会出现在Activity中,然而从上述代码中可以明显看出,再次重建了新的Fragment,导致了多个Fragment重叠在一起。解决方法:
//记录Fragment的位置
private int position = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_index);
setTabSelection(position);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
position = savedInstanceState.getInt("position");
setTabSelection(position);
super.onRestoreInstanceState(savedInstanceState);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
//记录当前的position
outState.putInt("position", position);
}