I have an Activity that displays different Fragments and these fragments changed when the user select an item from the spinner in the ActionBar , I have refresh button on the ActionBar . If i want to tell the current displayed fragment to refresh it content using the refresh menu button on the ActionBar . should i implement a Listener that communicates with Fragments ? or should i use a BroadCastReciever to inform the Fragment to refresh . Which is better ?? i haven’t implement any of these .
I have an Activity that displays different Fragments and these fragments changed when the
Share
That is really not easy question.
From one side, Broadcast probably will be an overkill for such a simple task, so I’d recommend to use listeners. But..
But please, be sure you understand how Fragments work. If you intent to create them from code and immediately set listeners – that can work for first time. But you can have troubles with activity recreation, when system re-instantiates a fragment. In this case it can just use Fragment’s public empty constructor and your code can go wrong with listeners not-setted.
So I think the good idea will be to set listeners from Fragment itself, for example in
onAttach()oronStart. There you can get holding activity withgetActivity()and set listeners. The cons of this approach is that you must cast your Activity to specific class to access listener-methods, and this limits the fragment reusage in other Activities, so beware this fact.Hope it helps