引言:
项目出现一个很古老的用法,用ActivityGroup来实现View的切换效果。现在已经被SDK注释为Depreciate了,推荐用Fragment进行代替。还是看看生命周期如何走的。
结构:
MainActivity extends ActivityGroup,布局:FrameLayout、Button。
另两Activity:SecondActivity、ThirdActivity,用这两个Activity的DecorateView(就是Activity的整体View),作为FrameLayout的子View。同过Button进行切换
生命周期:
public void onClick(View view){
willShowOrdinal++;
if (willShowOrdinal == 3) {
willShowOrdinal = 1;
}
switch (willShowOrdinal) {
case 1:
changeContainerView(SecondActivity.class, "1");
break;
case 2:
changeContainerView(ThirdActivity.class, "2");
break;
default:
break;
}
}
private void changeContainerView(Class cLazzz, String id) {
container.removeAllViews();
Intent intent = new Intent(this, cLazzz);
container.addView(getLocalActivityManager().startActivity(id, intent).getDecorView());
}
因
为.startActivity(id, intent)中的id是固定的2,3。所以不会再切换时新开启SecondActivity或ThirdActivity。而只是相当于SecondActivity被部分遮挡时走的生命周期。等到退出APP后。假设当前SecondActivity显示,则是MainActivity.onStop先onStop再ThirdActivity.onStop,再SecondActivity.onStop;
下面是日志:先加入ThirdActivity,再切换,最后再显示为SecondActivity时按Home键。
10-23 15:01:40.042: I/test(14741): Third on create
10-23 15:01:40.042: I/test(14741): Third on Resume
10-23 15:01:45.352: I/test(14741): Third on Pause
10-23 15:01:45.432: I/test(14741): Second on create
10-23 15:01:45.432: I/test(14741): Second on Resume
10-23 15:01:47.402: I/test(14741): Second on Pause
10-23 15:01:47.402: I/test(14741): Third on Resume
10-23 15:01:47.902: I/test(14741): Third on Pause
10-23 15:01:47.902: I/test(14741): Second on Resume
10-23 15:02:01.872: I/test(14741): Second on Pause
10-23 15:02:01.872: I/test(14741): Main on Pause
10-23 15:02:02.452: I/test(14741): Main on Stop
10-23 15:02:02.452: I/test(14741): Third on Stop
10-23 15:02:02.452: I/test(14741): Second on Stop