Reputation: 1359
I'm trying to wrap my head around the order and process of removing and signaling events to the Activity from the fragments.
I am trying to just have one FragmentA which is a list of items, transition to FragmentB upon a button click which loads a form to add a new item, and then when FragmentB is done with the form, add that item into the list of FragmentA. (The Main Arraylist is stored in MainActivity).
Basically, I have one MainActivity which creates a FragmentA (which populates a list with items). I also have a FragmentB (which is a form that allows an item to be added to the list).
What I'm getting confused about is how to properly set up the callbacks. I understand how to implement the callback with just one Fragment (using this and this tutorials) but my confusion is this:
Which order is the correct one (if any)?
MainActivity 'creates' (transitions) FragmentA, FragmentA then transitions to FragmentB. FragmentB then sends the callback (adding a new item) to FragmentA, and FragmentA signals to the MainActivity to add the item to the main list (callback 2). MainActivity then closes FragmentB. (I want to leave FragmentA open).
MainActivity 'creates' (transitions) FragmentA, FragmentA then transitions to FragmentB. FragmentB then sends the callback (adding a new item) to MainActivity. MainActivity then closes FragmentB and returns the state back to FragmentA.
MainActivity 'creates' (transitions) FragmentA, MainActivity then transitions to FragmentB when FragmentA signals a callback to switch fragments (close fragmentA or add it to the backstack). FragmentB sends a callback to MainActivity, MainActivity closes FragmentB and then reopens FragmentA.
Hopefully I explained it alright enough, but I know it is kind of confusing the way I worded it.
Edit
One last question, would the Activity end up "implementing" 15 different Fragment listeners if you had 15 different Fragments that needed callbacks? Just seems a bit excessive.
Thanks
Upvotes: 1
Views: 95
Reputation: 3150
Just consider the Activity
as a father and the Fragment
s are his children who have dependency to their father, So let the children make their wishes and the sugar daddy decides what is good for his sweethearts!
Main advantage of this approach is consistency and modularity of your code, Actually they have a server-client relationship, Fragment
s send their request and tasks are done by the Activity
, Each element plays its role in a clean and simple way.
Don't worry about number of interfaces you have to implement, But remember why an Activity
exists So you can easily realize Fragment
s which should be managed with a specific Activity
.
BroadcastReceiver
and EventBus library are the other options for communication but not the best in your case!
Upvotes: 1