从片段中调用活动的方法 [英] Calling Activity methods from Fragment

查看:103
本文介绍了从片段中调用活动的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用一个片段只在一个特定的父活动。现在,我不知道如果我叫方法父活动直接从包含片段像这样有什么弊端:

I use a fragment only inside one specific parent activity. Now I wonder if there are any drawbacks if I call methods in the parent activity directly from the included fragment like this:

getActivity()。someMethodInParentActivitiy()

getActivity().someMethodInParentActivitiy()

一个更常见的解决方案是定义了正式侦听接口的片段调用回父活动,然后使活动实现该接口。

A more common solution would be to define a formal listener interface in the fragment to call back to the parent activity and then make the activity implement that interface.

是否有任何理由(如可靠性速度的),我为什么要使用第二个更复杂的解决方案,而不是从片段活动的直接方法调用?

Are there any reasons (e.g. reliability or speed) why I should use the second more complex solution instead of direct method calls from the fragment to the activity?

推荐答案

不要看性能开始时。还记得premature的优化是一切罪恶的根源。第二种方法是更好,因为你的片段可以以不同的活动中使用。第一种方法引入了更多的依赖于你的code,该片段是依赖于活动类型。你也失去了能力测试,再利用,小复杂。这似乎现在更简单,但在未来,你会看到, - )

Don't look at the performance at the begining. Remember "premature optimization is the root of all evil". The second approach is better because your fragment could be used in different activities. The first approach introduces more dependencies in your code, the fragment is dependent to the activity type. You're loosing ability to test, reuse, small complex. It may seem to be simpler right now, but in the future you'll see ;-)

这篇关于从片段中调用活动的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆