One question for design about communicating between fragments,
why would someone use a bit complicated callback pattern implementing listeners,
versus using a simple static methods from a class we want to call a method from (something
similar to using Singleton for some methods/attributes).
Is there any performance issue or it is “just” a bad OO programming practice for Android/Java?
So the easy way for two-way communication could be:
MyActivity activity
Fragment A
Fragment B
static method canBeCalledFromAnywhere() {}
method activityMethod()
call FragmentA.doSomething();
call FragmentB.doSomething();
FragmentA
onCreate()
onMe = this;
static method doSomething()
do something with static or use onMe for instance;
method oneMethodFragmentA()
call MyActivity.canBeCalledFromAnywhere();
FragmentB
onCreate()
onMe = this;
static method doSomething()
do something with static or use onMe for instance;
method oneMethodFragmentB()
call MyActivity.canBeCalledFromAnywhere();
It’s better to use clearly specified communication interface than make assumption there is one. Therefore if you define
interfacefor your communication then:Fragmentcan easily check if parentActivityimplements thisinterface, so
Fragmentwill be able to communicate its needs,start coding, which leads to some sort of standardization and this is good,
if you change interface, but no implementation.
You may also want to read this Android SDK article.