在Android API 11+中,谷歌发布了一个名为Fragment的新类。
在视频中,谷歌建议,只要可能(link1, link2),我们应该使用片段而不是活动,但他们没有解释确切的原因。
片段的目的是什么以及它们的一些可能的用途(除了一些可以通过简单的视图/布局轻松实现的UI示例)?
我的问题是关于片段的:
使用片段的目的是什么?
与使用活动/视图/布局相比,使用片段的优点和缺点是什么?
奖金问题:
您能否为片段提供一些真正有趣的用途?谷歌在他们的视频里没有提到的事情?
在片段和包含它们的活动之间进行通信的最佳方式是什么?
当你使用片段时,最重要的事情是什么?从你的经验中有什么建议和警告吗?
不确定你指的是什么视频,但我怀疑他们说你应该使用片段而不是活动,因为它们不能直接互换。实际上,在开发指南中有一个相当详细的条目,考虑阅读它的详细信息。
In short, fragments live inside activities, and each activity can host many fragments. Like activities, they have a specific lifecycle, unlike activities, they are not top-level application components. Advantages of fragments include code reuse and modularity (e.g., using the same list view in many activities), including the ability to build multi-pane interfaces (mostly useful on tablets). The main disadvantage is (some) added complexity. You can generally achieve the same thing with (custom) views in a non-standard and less robust way.
#1 & #2使用片段的目的是什么
与使用片段相比,使用片段的优缺点
活动/视图/布局?
Fragments是Android用于创建可重用用户界面的解决方案。您可以使用活动和布局(例如使用include)来实现一些相同的功能。然而;fragments被连接到Android API中,从HoneyComb开始。让我详细说明;
The ActionBar. If you want tabs up there to navigate your app, you quickly see that ActionBar.TabListener interface gives you a FragmentTransaction as an input argument to the onTabSelected method. You could probably ignore this, and do something else and clever, but you'd be working against the API, not with it.
The FragmentManager handles «back» for you in a very clever way. Back does not mean back to the last activity, like for regular activities. It means back to the previous fragment state.
You can use the cool ViewPager with a FragmentPagerAdapter to create swipe interfaces. The FragmentPagerAdapter code is much cleaner than a regular adapter, and it controls instantiations of the individual fragments.
Your life will be a lot easier if you use Fragments when you try to create applications for both phones and tablets. Since the fragments are so tied in with the Honeycomb+ APIs, you will want to use them on phones as well to reuse code. That's where the compatibility library comes in handy.
You even could and should use fragments for apps meant for phones only. If you have portability in mind. I use ActionBarSherlock and the compatibility libraries to create "ICS looking" apps, that look the same all the way back to version 1.6. You get the latest features like the ActionBar, with tabs, overflow, split action bar, viewpager etc.
奖金2
片段之间最好的沟通方式是意图。当你在Fragment中按下一些东西时,你通常会调用StartActivity(),并在上面有数据。意图被传递到您启动的活动的所有片段。