异常:java.lang.IllegalStateException: Fragment already active

使用Fragment传递参数,书写的代码为:

                //切换到第一页面
                if (fragone == null) {
                    fragone = new OneFragment();
                }
                Bundle bundle = new Bundle();
                bundle.putString("key", "哈哈");
                //将数据添加到fragment中
                fragone.setArguments(bundle);
                transaction.replace(R.id.frameLayout, fragone);

点击第一次的时候是没有问题的,当再次点击的时候,就会报出异常java.lang.IllegalStateException: Fragment already active
这里写图片描述

找到原因是:
之前的Fragment已经实例化了,不能再次传递数据。
通过源代码就可以看出:

    /**
     * Supply the construction arguments for this fragment.  This can only
     * be called before the fragment has been attached to its activity; that
     * is, you should call it immediately after constructing the fragment.  The
     * arguments supplied here will be retained across fragment destroy and
     * creation.
     */
    public void setArguments(Bundle args) {
        if (mIndex >= 0) {
            throw new IllegalStateException("Fragment already active");
        }
        mArguments = args;
    }

解决方法:
第一种:在fragment中添加一个全局变量设置setter和getter方法,在宿主activity通过setter与getter传递数据。

第二种:可以判断fragment只有在它第一次实例化时候传递参数。

第三种:判断fragment不等于null的时候将它置为空再次实例化它。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值