片段到活动通信的Android最佳实践 [英] Android best practices for Fragment to Activity communications

查看:139
本文介绍了片段到活动通信的Android最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Android Fragment的新手,并尝试学习片段到活动的通信。
Android中的片段间活动通信有什么更好的方法(最佳实践)?



可以说我有FragmentA和ActivityA。
在我的屏幕弹出窗口FragmentA后,我想在ActivityA中执行somemethod(可能与UI相关)

这里有两个(模式)可能
解决方案:


  1. 在FragmentA getActivity中,将Activity转换为ActivityA,然后调用some方法。 $ b
  2. 在FragmentA中创建一个接口回调,然后在ActivityA中实现该回调。然后在回调中调用somemethod。

在Android开发中哪种模式更为常见/为什么。或者您有更好的方式在Android中与片段进行交流以与我分享?



任何意见,观点和建议都受到高度赞赏和欢迎。第二种解决方案是首选解决方案,因为它允许您的片段更加独立于其托管活动。

如果将来您决定将片段放在不同的活动上,那么片段上不需要进行任何更改,并且您只需要在您的活动。

我将添加第三个使用事件总线(例如Otto)的解决方案,虽然有些人可能会争辩说它会使您的代码成为可读性稍差。


I am new to Android Fragment and trying to learn Fragment to Activity communications. What is the better approach(best practice) in Android for Fragment to Activity communication?

Lets say I have FragmentA and ActivityA. After my screen popups FragmentA, I would like to perform somemethod(probably UI related) in ActivityA

Here are two(pattern) possible Solutions:

  1. In FragmentA getActivity and cast the Activity to ActivityA and then call somemethod.
  2. In FragmentA create an interface callback and then implement that callback in ActivityA. Then on the callback, call somemethod.

Which pattern is more common/perfer in Android development and why. Or do you have an even better way to communicate from fragment to activity in Android to share with me?

Any comments, opinions, and suggestions is highly appreciated and welcome. ^^ .

解决方案

The second solution is the preferred one, because it allows your fragment to be more independent of its hosting activity.

If in the future you decide to put your fragment on a different activity, there are no changes needed on the fragment, and you will only need to implement the interface on your activity.

I'll add a third solution which is using an event bus (Otto for instance), which also works, although some might argue that it makes your code a little less readable.

这篇关于片段到活动通信的Android最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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