最佳实践 - 片段和活动之间的通信。 [英] Communicating between a fragment and an activity - best practices.

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

问题描述

这个问题主要是征求对来处理我的应用程序的最佳方式的意见。我有三个片段由一个活动来处理。片段A有一个可点击的元素的照片和片段B有4个可点击的元素的按钮。另一个片段只是显示细节照片被点击时。我使用ActionBarSherlock。

This question is mostly to solicit opinions on the best way to handle my app. I have three fragments being handled by one activity. Fragment A has one clickable element the photo and Fragment B has 4 clickable elements the buttons. The other fragment just displays details when the photo is clicked. I am using ActionBarSherlock.

的前进和后退按钮需要更改的照片到下一个或previous构成,分别为。我可以保持照片并在同一个片段上的按钮,但希望让他们分开的情况下,我想重新安排他们在一个平板电脑。

The forward and back buttons need to change the photo to the next or previous poses, respectively. I could keep the photo and the buttons in the same fragment, but wanted to keep them separate in case I wanted to rearrange them in a tablet.

我需要一些建议 - 我应该结合片段A和B?如果没有,我需要找出如何实现一个接口为3点击物品。

I need some advice - should I combine Fragments A and B? If not, I will need to figure out how to implement an interface for 3 clickable items.

我考虑过使用Roboguice,但我用SherlockFragmentActivity所以这是一个不走已经延伸。只见一提的奥托,但是我没有看到如何在一个项目中包括很好的教程。你觉得最好的设计做法应该是什么?

I considered using Roboguice, but I am already extending using SherlockFragmentActivity so that's a no go. I saw mention of Otto, but I didn't see good tutorials on how to include in a project. What do you think best design practice should be?

我还需要帮助搞清楚如何在碎片和活动之间进行通信。我想保留一些数据全球性的应用程序,如姿势ID。有一些例如code除了普通的Andr​​oid开发者的信息,我能看到什么?那是不是所有的帮助。

I also need help figuring out how to communicate between a fragment and an activity. I'd like to keep some data "global" in the application, like the pose id. Is there some example code I can see besides the stock android developer's information? That is not all that helpful.

顺便说一句,我已经存储每个的所有信息造成的SQLite数据库。这是比较容易的部分。

BTW, I'm already storing all the information about each pose in a SQLite database. That's the easy part.

推荐答案

最简单的就是使用接口你的活动和片段之间进行通信的方式。这个想法基本上是定义一个给定的片段A内的界面,让活动实现该接口。

The easiest way to communicate between your activity and fragments is using interfaces. The idea is basically to define an interface inside a given fragment A and let the activity implement that interface.

一旦它实现这个接口,你可以做你希望在它覆盖的方法什么。

Once it has implemented that interface, you could do anything you want in the method it overrides.

接口的另一个重要组成部分是,​​你必须从你的片段调用抽象方法,并记住它转换为您的活动。它应该捕获ClasCastException如果没有正确完成。

The other important part of the interface is that you have to call the abstract method from your fragment and remember to cast it to your activity. It should catch a ClasCastException if not done correctly.

有在如何做的正是简单的开发者博客这种事情。

我希望这是对您有所帮助!

I hope this was helpful to you!

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

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