Reputation: 3816
How can I get my activity to update a fragment it controls? It goes like this, I have a DatePickerDialog, that when your in the Fragment its called. I have a call back to the activity to let it know when this datepickerdialog is done having a date selected that passes back the date selected. So my activity has it, but I want the Fragment that called the DialogFragment to have access to it, instead of the activity above. Is this possible?
So I have this EditSessionActivity
, that in it calls the SessionEdit Fragment
. Which loads the fragment with UI and a date button, when that is clicked a DialogFragment
called DatePickerDialogFragment
is launched, this works great, and calls back to the EditSessionActivity
that implements the OnDialogDoneListner
that I wrote. The data is there, but I want to push that data back to the SessionEdit
fragment to update its UI. How would I go about doing this?
Earlier today I thought I was going to easily get this to work, tried to answer something here:
How to create datePicker and timePicker dialogs in fragment class?
realizing that my UpdateDisplay (From the link above) there in the above link does zilch for updating the buttons text from the calling fragment like I want.
Upvotes: 3
Views: 7770
Reputation: 1763
A Fragment is going to need to communicate with its parent Activity and vice versa. Define an interface for both to conform to and allow appropriate listeners to subscribe to events. For example, I would say that any time a fragment wants to change the UI outside itself, this should be delegate to the Activity. One Fragment shouldn't know or care if other Fragments exist. (To be comical, if the Fragment wants a sandwich it should call 'sudo make me a sandwich')
Let's say this is an email client and the Fragment wants the user to select an attachment. It should call something like MyParentActivity.selectAttachment(AttachmentSelectedCallback). If this is a tablet, maybe the Activity invokes a new fragment, leaving the compose fragment visible. If this is a phone, maybe a new Activity is started or the existing Fragment is swapped out for the attachment selector.
One way I'm thinking about an Activity/Fragment relationship is the way microkernels are designed. The Activity is the kernel, the Fragment is a service. The kernel manages communication and spinning up or shutting down the services, but generally speaking services shouldn't be directly aware of one another. Note there are performance penalties to this design that are not always worth the tradeoff.
Upvotes: 9
Reputation: 7120
If you see the TitleFragment
example in this page : http://developer.android.com/guide/topics/fundamentals/fragments.html
You will see a new instance of the DetailsFragment
is created everytime a new index in the TitleFragment
is created instead of updating the existing UI itself. You might want to create a new instance of the fragment every time you want to change the view.
Upvotes: 1