“碎片已经主动”setArguments(),以片段时, [英] 'Fragment already active' when setArguments() to fragment

查看:114
本文介绍了“碎片已经主动”setArguments(),以片段时,的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个活动那里举办的片段

活动布局文件:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <fragment class="com.my.ContentFragment"
        android:id="@+id/fragment_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</FrameLayout>

Java的$ C $了C 活动

import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;

public class ContentActivity extends ActionBarActivity {

     @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            setContentView(R.layout.activity_main);

            //data from  previous Activity
            Bundle data = getIntent().getExtras();

            Fragment contentFragment = getSupportFragmentManager()
                                                    .findFragmentById(R.id.fragment_content);

            //Pass data to fragment
            /*java.lang.IllegalStateException: Fragment already active*/
            contentFragment.setArguments(data);

        }
...   
}

我试图找到的onCreate活动的()片段,然后一些数据传递给它。但是,当我 contentFragment.setArguments(数据); ,我得到的 java.lang.IllegalStateException:碎片已激活

I try to find the fragment in onCreate() of Activity, and then pass some data to it. But when I contentFragment.setArguments(data);, I got java.lang.IllegalStateException: Fragment already active.

然后我还检查 contentFragment.getArguemtns()这是空。那么,我为什么不能设置参数,我的片段?

Then I also checked contentFragment.getArguemtns() which is null. So, why I can not set argument to my fragment?

如果它是不可能通过捆绑的情况下碎片这样,我怎么能传递束片段?

If it is not possible to pass bundle to fragment this way, how can I pass the bundle to fragment?

推荐答案

参数通常读 Fragment.onCreate()。如果你从充气XML布局的片段,然后将片段已通过FragmentManager到活动添加的,不能接受参数了。

Arguments are typically read in Fragment.onCreate() .. If you inflate the Fragment from xml layout, then the fragment is already added through the FragmentManager to the activity and can not take arguments anymore.

如果一个片段需要观点是更好地为您将其添加到 FragmentManager 编程而不是使用XML的方式。我鼓励你看看到文档,其中解释了正确的片段的生命周期,以及如何将该片段连接到正确的活性。

If a fragment needs arguments it is better for you to add it to the FragmentManager programatically and not using the xml way. I encourage you to have a look to this doc where it is explained the correct fragment lifecycle and how to attach this fragment to the activity correctly.

顺便说一句。你可能会发现 FragmentArgs 有用的。

Btw. you may find FragmentArgs useful.

这篇关于“碎片已经主动”setArguments(),以片段时,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆