安卓:片段之间跳跃的正确方法 [英] Android: correct way of jumping between fragments

查看:186
本文介绍了安卓:片段之间跳跃的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个设计问题,而不是技术问题。

This is a design question, rather than a technical one.

常规情况下:我想在一个片段的UI事件,使活动范围的更改

General case: I want an UI event in a Fragment to make Activity-wide changes.

的具体情况:我有两个片段,在举办相同的活动。当用户点击一个按钮,在这些片段中的一个,我希望它被其他所取代。

Specific case: I have two fragments, hosted in the same activity. When the user clicks a button in one of those fragments, I want it to be replaced by the other.

我不想,但是,我的碎片摸我的活动。我想在以后去改变(也许,在一个更​​大的屏幕,显示的不是替换第一两个片段),我不希望我的片段code有这种逻辑。

I don't want, however, my Fragments touching my activity. I may want to change the behavior later (maybe, in a bigger screen, show both fragments instead of replacing the first), and I don't want my Fragment code to have that logic.

我所做的就是实施监听器类在我的片段,该报告的事件回活动。这样,如果我想使用其他活动类不同的显示的行为,我可以改变的监听器和离开片段 code不变。

What I did was implement a Listener class in my fragments, that reports events back to the Activity. This way, if I want to use another Activity class with different display behavior, I can just change the listener and leave the Fragment code untouched.

这是一个很好的方式去了解它?是否有一个标准的好习惯,或者更好的设计模式?

Is this a good way to go about it? Is there a standard good practice, or a better design pattern?

推荐答案

使用监听器是碎片和您的活动之间进行通信的推荐方法。

Using listeners is the recommended way of communicating between Fragment and your activity.

请参阅此<一个href="http://developer.android.com/guide/topics/fundamentals/fragments.html#CommunicatingWithActivity">Android documentatin部分为infromation。长话短说,他们只是落实Activity类的监听器接口和投getActivity()导致片段给听众。

See this Android documentatin section for infromation. Long story short they just implement a listener interface by the Activity class and cast getActivity() result in a fragment to a listener.

从我个人的经验,这是非常方便,因为可以让你:

From my personal experience this is very convenient because lets you to:

  1. Easilly切换基本活动(例如,你在一个包装活动主办整个片段中的pre-3.0的兼容性和与人相处的11举办这个片段+)
  2. Easilly控制,如果包装活动支持回调与否。只是检查是它确实实现了监听器,做您的应用程序的具体行动,如果它没有。

这篇关于安卓:片段之间跳跃的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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