我已经开始开发 Android 应用程序,我想知道在向活动添加片段的情况下哪种方式更好。让我们假设活动视图始终包含三个片段。他们不会改变。永远一样。因此,最好通过标签添加它们还是将它们包含在活动代码中?
第二个问题:假设我有一个片段的活动,它是一个列表。然后,当我单击项目时,我想显示新视图。然后我可以用新的完全不同的片段替换列表片段吗?即使答案是肯定的,那是否比创建新活动更好?
感谢所有回复
我已经开始开发 Android 应用程序,我想知道在向活动添加片段的情况下哪种方式更好。让我们假设活动视图始终包含三个片段。他们不会改变。永远一样。因此,最好通过标签添加它们还是将它们包含在活动代码中?
第二个问题:假设我有一个片段的活动,它是一个列表。然后,当我单击项目时,我想显示新视图。然后我可以用新的完全不同的片段替换列表片段吗?即使答案是肯定的,那是否比创建新活动更好?
感谢所有回复
which way is better in case of adding fragments to activity
One approach is not necessarily 'better' than the other - they both serve their own purposes, as with any static vs. dynamic comparison.
For example, fragments declared in a layout cannot be given arguments using setArguments()
. Such a fragment can also not be replaced by another fragment: if it's part of the layout, it'll always be there. Of course you can still show/hide the instance, but attempting to actually remove it through a FragmentTransaction
will simply not work. Static elements are usually easier to work with though, because they have a well-defined lifetime and behaviour.
Regarding your second question: yes, that's very possible. Some developers build their app around a single Activity
container, swapping out fragments as the user navigates its way through the content. In most cases, from a user's point of view, there is little difference between doing this or having multiple activities. The important thing to keep in mind is to choose an approach you're comfortable with, doesn't overly complicate things and takes advantage of the patterns explained in Implementing Effective Navigation.