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

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

问题描述

这个问题主要是征求对处理我的应用程序的最佳方式的意见.我有一个活动正在处理三个片段.片段 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.

前进和后退按钮需要分别将照片更改为下一个或上一个姿势.我可以将照片和按钮保存在同一个片段中,但希望将它们分开,以防我想在平板电脑中重新排列它们.

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 进行扩展,所以这是行不通的.我看到提到 Otto,但我没有看到关于如何包含在项目中的好的教程.您认为最佳设计实践应该是什么?

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.除了股票android开发人员的信息之外,我还能看到一些示例代码吗?这并不是很有帮助.

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.

推荐答案

在 Activity 和 Fragment 之间进行通信的最简单方法是使用接口.这个想法基本上是在给定的片段 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.

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

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 ClassCastException if not done correctly.

简单开发者博客上有一个很好的教程关于如何做这种事情.

There is a good tutorial on Simple Developer Blog on how to do exactly this kind of thing.

希望对你有帮助!

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

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