问题
I have an Activity which hosts a Fragment.
The Activity layout file:
<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 code of Activity:
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);
}
...
}
I try to find the fragment in onCreate() of Activity, and then pass some data to it. But when I contentFragment.setArguments(data);, I get java.lang.IllegalStateException: Fragment already active.
Then I also checked contentFragment.getArguments() which is null. So, why I can not set arguments to my fragment?
If it is not possible to pass bundle to fragment this way, how can I pass the bundle to fragment?
回答1:
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.
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.
Btw. you may find FragmentArgs useful.
回答2:
Just use FrameLayout in your xml file instead of fragment tag.
Then just create new Fragment object from onCreate() of your activity [above] and call fragment.setArguments(Bundle);.
And inside onCreate() of Fragment class, call getArguments(), which will return passed Bundle.
It is best approach ever to pass bundle to Fragment.
来源:https://stackoverflow.com/questions/29194026/fragment-already-active-when-setarguments-to-fragment