我有一个FragmentActivity,它包含一个Fragment(ContainerFragment)和一个FragmentStatePagerAdapter,它也嵌套了两个片段(一个地图和一个列表)。为了在方向更改后没有获得nullpointer,我必须设置ContainerFragment setRetainInstance(true),嵌套的Fragments不能是setRetainInstance(true),因为会有一个异常“无法保留嵌套的片段”。方向改变一切正常,但是当我从ListFragement开始一个新的细节片段时,我得到“在onSaveInstanceState之后无法执行此操作”
我搜索了两个例外的答案,但对我没什么用。
MainActivity中的:
containerFragment = new ContainerFragment();
FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction();
if (findViewById(R.id.fragment_container) != null) {
transaction
.replace(R.id.fragment_container, containerFragment );
}
transaction.addToBackStack(null);
transaction.commit();
在ContainerFragment中:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Retain this fragment across configuration changes.
// If not set, there is a NPE on orientation change
setRetainInstance(true);
// load slide menu items
mTabStrings = getResources().getStringArray(R.array.tabs_array);}
public class MyPagerAdapter extends FragmentStatePagerAdapter {
public MyPagerAdapter (FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int i) {
switch (i) {
case 0:
MapFragment mapFragment = (MapFragment ) Fragment
.instantiate(getActivity(),
MapFragment .class.getName());
return mapFragment ;
case 1:
ListFragment listFragment = (ListFragment ) Fragment
.instantiate(getActivity(),
ListFragment .class.getName());
return listFragment ;
default:
ListFragment listFragment = (ListFragment ) Fragment
.instantiate(getActivity(),
ListFragment .class.getName());
return listFragment ;
}
并且主要活动中的此方法是从ListFragment触发的,并且在方向更改之前有效,但在之后没有,在“事务发生”()之后“无法在onSaveInstanceState之后执行此操作”
@Override
public void onItemSelected(int position) {
// Create fragment and give it an argument for the selected article
XYFragment xyFragment = new XYFragment ();
FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction();
// Replace whatever is in the fragment_container view with this
// fragment,
// and add the transaction to the back stack so the user can
// navigate back
if (findViewById(R.id.fragment_container) != null) {
transaction.replace(R.id.fragment_container, xyFragment);
}
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}