我按照以下方式在framelayout中添加了片段
mUserListFragment = new UserListFragment();
mMessageFragment = new MessageFragment();
mAccountFragment = new AccountFragment();
fragmentManager.beginTransaction().add(R.id.frame_layout, mAccountFragment, mAccountFragment.getClass().getSimpleName()).addToBackStack(mAccountFragment.getClass().getSimpleName()).commit();
fragmentManager.beginTransaction().add(R.id.frame_layout, mMessageFragment, mMessageFragment.getClass().getSimpleName()).addToBackStack(mMessageFragment.getClass().getSimpleName()).commit();
fragmentManager.beginTransaction().add(R.id.frame_layout, mUserListFragment, mUserListFragment.getClass().getSimpleName()).addToBackStack(mUserListFragment.getClass().getSimpleName()).commit();
稍后我会以以下方式显示或隐藏片段
//for showing
fragmentManager.beginTransaction().show(fragment).commit();
//for hiding
fragmentManager.beginTransaction().hide(fragment).commit();
从片段的其中一个,我通过一些onClick方法转到另一个Activity,然后该Activity重定向到保存这些片段的同一活动。回到片段持有者的活动时,我将片段重新加载到onResume
中,但它使该片段为空白,但是通过调试,我知道片段可见,并且调用了onCreateView
方法,我尝试按照以下方式重新加载片段
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.setReorderingAllowed(false);
ft.detach(activeFragment).commitNow();
ft.attach(activeFragment).commitNow();
我也尝试过
fragmentManager.beginTransaction().detach(activeFragment).attach(activeFragment).commitAllowingStateLoss();
所有这些都只留下空白屏幕。
答案 0 :(得分:1)
您可以通过以下代码跟踪片段的堆栈和片段计数。
getSupportFragmentManager().addOnBackStackChangedListener(new OnBackStackChangedListener() {
public void onBackStackChanged() {
Log.i(TAG, "back stack changed ");
int backCount = getSupportFragmentManager().getBackStackEntryCount();
// you can also track which are current fragments are in stack by
getSupportFragmentManager().getFragments();
if(backCount ==0){
//then you have to check whats going wrong in your case
// suppose to kill current activity also by finish();
// I means its depending on your requirements.
}
}
});
它将帮助您找到自己的出路。
答案 1 :(得分:-1)
您需要通过newInstanse()方法创建片段。
public class YourFragment extends Fragment {
public static YourFragment newInstance() {
Bundle args = new Bundle();
YourFragment fragment = new YourFragment();
fragment.setArguments(args);
return fragment;
}
}
活动中:
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content,YourLoanFragment.newInstance(),tag)
.commit();