返回嵌套的viewpager时恢复状态会导致崩溃
作者:互联网
我有一个添加ParentFragment的按钮.里面有一个Viewpager,其中包含两个ListFragments.第一次添加ParentFragment时,一切正常,除非我按回并再次添加ParentFragment. ParentFragment照常创建,但是当它尝试创建Viewpager时,它将以某种方式使应用程序崩溃.
ParentFragment
|
V
ListFragment 1 <-- Viewpager --> ListFragment 2
错误日志:
FATAL EXCEPTION: main
Process: at.umoser.fab.musikbox, PID: 16900
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference
at android.support.v4.app.FragmentManagerImpl.getFragment(FragmentManager.java:667)
at android.support.v4.app.FragmentStatePagerAdapter.restoreState(FragmentStatePagerAdapter.java:211)
at android.support.v4.view.ViewPager.onRestoreInstanceState(ViewPager.java:1319)
at android.view.View.dispatchRestoreInstanceState(View.java:13639)
at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:2889)
at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:2895)
at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:2895)
at android.view.View.restoreHierarchyState(View.java:13617)
at android.support.v4.app.Fragment.restoreViewState(Fragment.java:468)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1094)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1248)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1613)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5312)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
这就是我在’ParentFragment **中使用getChildFragmentManager()调用Viewpager的方式:
mPager = (ViewPager) rootView.findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getChildFragmentManager(), connection);
mPager.setAdapter(mPagerAdapter);
显然,使用getChildFragmentManager()而不是使用getFragmentManager()是嵌套片段的正确方法,尽管使用getFragmentManager()时应用程序不会崩溃,但viewpager根本不会出现.
Viewpager或其适配器是否每次创建时都调用onRestoreInstanceState / restoreState方法(检查错误日志),还是仅在第二次添加ParentFragment时才发生?
如果是这样,我如何强迫它从头开始创建所有内容,而不是恢复状态?还是有其他解决方案.
解决方法:
我避免了使用FragmentPagerAdapter而不是ViewPager Adapter的FragmentStatePagerAdapter来恢复状态.我使用Android文档来创建适配器,却错过了多个传呼适配器…太笨了.
标签:fragmentmanager,android-fragments,android-viewpager,java,android 来源: https://codeday.me/bug/20191027/1943463.html