我有一个ViewPager
,当应用启动时会被FragmentStatePagerAdapter
填充:
ViewPager mViewPager;
...
@Override
public void onViewCreated(View view, Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
mViewPager = (ViewPager) view.findViewById(R.id.viewpager);
mViewPager.setAdapter(new PageAdapter(getChildFragmentManager()));
//PageAdapter extends from FragmentStatePagerAdapter
}
这样可以正常工作。
现在,当用户更改应用程序的设置时,我想将新的适配器分配给ViewPager,如下所示:
@Override
public void updateObserver(SETTING_KEY key)
{
mViewPager.setAdapter(new PageAdapter(getChildFragmentManager()));
Log.d("info", "updating");
}
不幸的是,在使用此例外调用updateObserver
后应用程序崩溃了:
01-22 23:22:45.957:E / AndroidRuntime(13131):致命异常:主要 01-22 23:22:45.957:E / AndroidRuntime(13131):java.lang.IllegalStateException:键f0不再存在Fragement:index 0 01-22 23:22:45.957:E / AndroidRuntime(13131):在android.support.v4.app.FragmentManagerImpl.getFragment(FragmentManager.java:575) 01-22 23:22:45.957:E / AndroidRuntime(13131):在android.support.v4.app.FragmentStatePagerAdapter.restoreState(FragmentStatePagerAdapter.java:211) 01-22 23:22:45.957:E / AndroidRuntime(13131):在android.support.v4.view.ViewPager.onRestoreInstanceState(ViewPager.java:1281) 01-22 23:22:45.957:E / AndroidRuntime(13131):在android.view.View.dispatchRestoreInstanceState(View.java:13188) 01-22 23:22:45.957:E / AndroidRuntime(13131):在android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:2850) 01-22 23:22:45.957:E / AndroidRuntime(13131):在android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:2856) 01-22 23:22:45.957:E / AndroidRuntime(13131):在android.view.View.restoreHierarchyState(View.java:13166) 01-22 23:22:45.957:E / AndroidRuntime(13131):在android.support.v4.app.Fragment.restoreViewState(Fragment.java:425) ...
如何在不崩溃应用程序的情况下将新适配器分配给ViewPager
?
答案 0 :(得分:1)
使用getFragmentManager()而不是getChildFragmentManager()。