I want to pass arguments from my activity to a fragment, embedded into the activity. Fragment is embedded statically in xml layout. I tried to call setArgument() like this:
setContentView(R.layout.detail_activity);
DetailFragment detailFragment = (DetailFragment) getFragmentManager().findFragmentById(R.id.detailFragment);
detailFragment.setArguments(getIntent().getExtras());
but it is already too late, because setArguments has to be called immediately after fragment's creation. The only was I see it to getArguments() and the change the bundle. Any better way?
AFAIK, you can't use
setArguments()
like that when you embed the fragment within XML. If it's critical, you'd be better off dynamically adding the fragment instead. However if you truly want the fragment to be embedded via XML, there are different ways you can pass along that data.onCreate()
method, then do it from the activity'sonAttachFragment()
method.Another way to pass data to Fragment is as following:
And when attaching DetailFragment from inside Activity
You have two options here
If you just need information in the activity's intent, then placing information from the intent into the fragment arguments just adds an unneeded step. You might just a well keep things simple and from your fragment call
If you need to add information that is not in the activity's intent then in you fragment create a no parameter constructor like:
then in your activity you can add whatever arguments you need with code like:
the point here is to use the existing bundle object rather than trying to call setArguments() after the fragment has been attached to the activity.