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?
Therefore, in order to pass your data to the Fragment being created, you should use the setArguments() method. This methods gets a bundle, which you store your data in, and stores the Bundle in the arguments. Subsequently, this Bundle can then be retrieved in onCreate() and onCreateView() call backs of the Fragment.
To pass info to a fragment , you setArguments when you create it, and you can retrieve this argument later on the method onCreate or onCreateView of your fragment. Then inside the fragment on the method onCreate or onCreateView you can retrieve the arguments like this: Bundle args = getArguments(); int index = args.
Add a fragment to an activity You can add your fragment to the activity's view hierarchy either by defining the fragment in your activity's layout file or by defining a fragment container in your activity's layout file and then programmatically adding the fragment from within your activity.
If you want to access the view in your activity from within your fragment class, use getActivity() to access the activity to which your fragment is attached, and from there you find your TextView. Show activity on this post. How about adding a set function in your custom fragment e.g. Show activity on this post.
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's onAttachFragment()
method.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With