java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child’s parent first.错误解决。
在使用viewpager切换fragment的时候有可能会遇到该问题,直接导致项目崩溃。
解决办法是:尝试在代码中加入
mMainVp.setOffscreenPageLimit(5);
具体个数根据framgment数量来确定
拷贝一下该方法的注释:
Set the number of pages that should be retained to either side of the
* current page in the view hierarchy in an idle state. Pages beyond this
* limit will be recreated from the adapter when needed.
*
* <p>This is offered as an optimization. If you know in advance the number
* of pages you will need to support or have lazy-loading mechanisms in place
* on your pages, tweaking this setting can have benefits in perceived smoothness
* of paging animations and interaction. If you have a small number of pages (3-4)
* that you can keep active all at once, less time will be spent in layout for
* newly created view subtrees as the user pages back and forth.</p>
*
* <p>You should keep this limit low, especially if your pages have complex layouts.
* This setting defaults to 1.</p>
*
* @param limit How many pages will be kept offscreen in an idle state.
其中提到当页面比较少量(3-4)个页面,是不需要额外操作就可以实现缓存。
如果多的话,数据就会被清除掉;
比如当五个页面的情况,如果不加该方法,只能保持4个页面的缓存数据,根据入栈和出栈原则,最先缓存的页面会被清除掉,所以切换的时候有可能会找不到一开始的index(因为被清除掉了)就可能会崩溃。
或者还有一种情况是重复加载。
如果想更深入的了解,可以加入生命周期打印日志查看活动的流程。
比如我在Activity中设置了mMainVp.setOffscreenPageLimit(4);
然后在一个FragmentManager中打印日志,发现会一次性加载完所有的页面。