在片段和活动之间进行交流-最佳做法 [英] Communicating between a fragment and an activity - best practices
问题描述
这个问题主要是为了征询关于处理我的应用程序的最佳方法的意见.我有一个活动正在处理三个片段.片段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?
我还需要帮助弄清楚如何在片段和活动之间进行通信.我想在应用程序中保留一些全局"数据,例如pose 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.
推荐答案
在活动和片段之间进行通信的最简单方法是使用接口.这个想法基本上是在给定的片段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.
接口的另一个重要部分是您必须从片段中调用abstract方法,并记住将其强制转换为活动.如果处理不正确,它将捕获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屋!