片段活动交流,相互沟通的片段 [英] Fragment-Activity communication, and inter-fragment communication
问题描述
设计有关片段之间沟通的一个问题,
为什么要使用一个有点复杂回调格局实施监听器,
与使用从一个类简单的静态方法我们要调用从(东西的方法
类似于使用单件为一些方法/属性)。
是否有任何性能问题或者是只是一个坏的面向对象编程为Android / Java的做法?
因此,对于进行双向通信的简单的方法可以是:
MyActivity活动
片段A
片段B
静态方法canBeCalledFromAnywhere(){}
方法activityMethod()
调用FragmentA.doSomething();
调用FragmentB.doSomething();碎裂
的onCreate()
onMe =这一点;静态方法DoSomething的()
做一些静态或使用onMe例如;方法oneMethodFragmentA()
调用MyActivity.canBeCalledFromAnywhere();FragmentB
的onCreate()
onMe =这一点;静态方法DoSomething的()
做一些静态或使用onMe例如;方法oneMethodFragmentB()
调用MyActivity.canBeCalledFromAnywhere();
这是更好地使用明确规定的通讯接口不是做出假设有一个。因此,如果你定义接口
为您的沟通,则:
- 您
片段
可以很容易地检查,如果父活动
实现此
接口,所以片段
将能传达其需求, - 要定义的接口,你需要想好了一点,而不是只
开始编码,从而导致某种标准化的,这是不错的, - 可以很容易地保持界面的更新,因为编译器会抱怨
如果更改接口,但没有实现。
您可能还需要阅读这个Android SDK中文章。
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 interface
for your communication then:
- your
Fragment
can easily check if parentActivity
implements this interface, soFragment
will be able to communicate its needs, - to define interface you need to think it over a bit instead of just start coding, which leads to some sort of standardization and this is good,
- it's easy to maintain updates of interface as compiler will complain if you change interface, but no implementation.
You may also want to read this Android SDK article.
这篇关于片段活动交流,相互沟通的片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!