为什么在同一个 Activity 中使用两个或更多片段?

Why using two or more fragments in the same Activity?

我是初学者 android 开发人员,现在我正在学习 android 中的片段,所以当我读到它时:

A fragment is just a part of an activity. You can have a fragment that takes up part of a screen or a whole screen. Or you can show multiple fragments at the same time to make up a whole screen. Within an activity, you can also swap out different fragments with each other. (You can also have invisible fragments as well, that do some work related to the activity, but we won’t cover those in this course.)

Fragments were introduced in Android when we started building for larger screen devices like tablets. Let me show you an example.

In the master/detail pattern, a list fragment is on the left side of the screen, while the detail fragment on the right swaps out depending on the list item selected.

所以,我想问一下,fragments除了适配大屏还有什么用? 谢谢!!

它主要是关于可重复使用的 UI 和独立的代码。

在更大的项目中,这些可以派上用场。

您还可以根据设置动态配置屏幕上的内容,也许 a/b 测试、远程配置等,无需大量重写代码。如果团队成员是独立的,则他们可以独立地处理代码部分。组件可以在其他活动中使用不同的配置进行测试。

所以这真的取决于你的用例。

您可以将片段视为 activity 的模块化部分,它有自己的生命周期,接收自己的输入事件,并且您可以在 activity 运行时添加或删除片段运行(有点像可以在不同活动中重复使用的 "sub activity")。

来源:developer.android.com/guide/components/fragments