java.lang.IllegalStateException: The specified child already has a parent错误解决

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中打印日志,发现会一次性加载完所有的页面。

日志

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值