我在第一层fragment里嵌套了两个子fragment,运行之后第一次点击到第一层fragment,可以显示对应的两个子fragment的内容,但是切换到第一层别的fragment之后再切换回来,这层的两个子fragment都无法显示了。我看了两个fragmen的生命周期,发现选中之后执行到onResume,之后点击到另一个时没有onPause及其之后的周期
其中相关代码如下
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
Log.i(TAG, "onCheckedChanged: " + "checkedId:" + checkedId);
switch (checkedId) {
case R.id.faqi:
// System.out.println("我发起的");
setChioceItem(0);
break;
case R.id.canyu:
// System.out.println("我参与的");
setChioceItem(1);
break;
}
}
private void setChioceItem(int index) {
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
// clearChioce(); // 清空, 重置选项, 隐藏所有Fragment
// Log.i(TAG, "setChioceItem: " + (sponsorGroupActivityFragment == null) + " " + (participateGroupActivityFragment == null));
hideFragments(fragmentTransaction);
switch (index) {
case 0:
if (sponsorGroupActivityFragment == null) {
sponsorGroupActivityFragment = new SponsorGroupActivityFragment();
fragmentTransaction.add(R.id.discovery_frag_frag, sponsorGroupActivityFragment);
} else {
// 如果不为空,则直接将它显示出来
fragmentTransaction.show(sponsorGroupActivityFragment);
}
break;
case 1:
if (participateGroupActivityFragment == null) {
participateGroupActivityFragment = new ParticipateGroupActivityFragment();
fragmentTransaction.add(R.id.discovery_frag_frag, participateGroupActivityFragment);
} else {
// 如果不为空,则直接将它显示出来
fragmentTransaction.show(participateGroupActivityFragment);
}
break;
}
fragmentTransaction.commit(); // 提交
}
private void hideFragments(FragmentTransaction fragmentTransaction) {
if (sponsorGroupActivityFragment != null) {
fragmentTransaction.hide(sponsorGroupActivityFragment);
}
if (participateGroupActivityFragment != null) {
fragmentTransaction.hide(participateGroupActivityFragment);
}
}
回复讨论(解决方案)
fragment的生命周期和Activity不通,它的生命周期大都是跟着Activity的,比如onResume这个方法,Fragment已经创建后,必须Activity调用 onResume 才会调用Fragment的,替换fragment并不会 走onResume,fragment会创建后会缓存
除非你每次Replace都new 新的Fragment 明白了,谢谢!!!!!!!