“碎片已经主动”setArguments(),以片段时,碎片、片段、主动、setArguments

2023-09-12 06:08:32 作者:折兰勾玉杏向晚

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

在活动布局文件:

<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.