I am currently making an android app, and I want to pass a date between activity and fragment. My activity has a button, which opens the fragment: DatePickerFragment.
In my activity I show a date, which I want to modify with the fragment. So I want to pass the date to the datepicker, and send it back to the activity.
I've tried a lot of solutions, but none are working. The easy way would pass an argument, but this can't be done with fragments.
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.
On the newInstance function of your fragment you add the arguments you wanna send to it:
Then inside the fragment on the method onCreate or onCreateView you can retrieve the arguments like this:
If you want now communicate from your fragment with your activity (sending or not data), you need to use interfaces. The way you can do this is explained really good in the documentation tutorial of communication between fragments. Because all fragments communicate between each other through the activity, in this tutorial you can see how you can send data from the actual fragment to his activity container to use this data on the activity or send it to another fragment that your activity contains.
Documentation tutorial:
http://developer.android.com/training/basics/fragments/communicating.html
You can simply instantiate your fragment with a bundle:
Sending data from
Activity
to aFragment
Activity:
Fragment:
Reading the value in fragment
But if you want to send values from Fragment to Activity, read the answer of jpardogo, you must need interfaces, more info: Communicating with other Fragments
thanks to @ρяσѕρєя K and Terry ... it helps me a lot and works perfectly
From Activity you send data with intent as:
and in Fragment onCreateView method:
reference : Send data from activity to fragment in android
Use the library EventBus to pass event that could contain your variable back and forth. It's a good solution because it keeps your activities and fragments loosely coupled
https://github.com/greenrobot/EventBus