何时以及为什么应该在 Android 应用程序中使用片段?

问题描述:

我经常需要我的应用程序的不同部分有自己的特殊行为和 UI,我不知道片段如何提供帮助.在大多数情况下,我认为创建 2 个不同的 Activity(例如,1 个用于平板电脑,1 个用于手机)并在第三个类*享常见的行为和事件会更快.

I often need the different parts of my applications to have their own special behavior and UI, and I don't know how fragments can help. In most cases, I think it is quicker to create 2 different activities (e.g., 1 for tablets and 1 for handsets), and to share the common behaviors and events in a third class.

所以,记住这一点,我为什么要使用片段?

So, keeping this in mind, why should I use fragments ?

在我看来,片段更像是一种 UI 好处.有时用户可以方便地在同一屏幕上看到两个不同类的两个不同视图.如果,在您创意的时刻,您决定使用一个占据屏幕一半的 listView 和一个占据另一半屏幕的 webView 来显示您的应用程序会很好 - 这样当您单击列表项时片段 A 它将意图传递给片段 B 中的 webView,然后您突然看到您刚刚单击的内容,而没有应用程序切换活动 - 然后您可以使用片段.这只是我突然想到的一个例子.

Fragments are more of a UI benefit in my opinion. It's convenient for the user sometimes to see two different views of two different classes on the same screen. If, in your moment of creativity, you decide it would be nice to display your application with, say, a listView that takes up half the screen and a webView that takes up the other half - so that when you click on a list item in fragment A it passes an intent to the webView in fragment B, and suddenly you see what you just clicked without the app switching activities - then you could use a fragment. That's just an example I came up with off the top of my head.

底线:Fragment 是屏幕上同时出现的两个或多个活动.

Bottom line: Fragments are two or more activities on the screen at the same time.