android - 如何跨导航堆栈重用android片段(Android中的iOS标签栏实现)?
问题描述
我正在构建一个 Android 应用程序来复制现有的 iOS 应用程序,并且我使用底部导航元素作为与 iOS 选项卡栏模式类似的核心应用程序结构。所以,我在应用程序中有一个只处理底部导航的主要活动。目前,我有 5 个选项卡,我用嵌套图的导航填充每个选项卡,就像在这个官方 Android 架构示例中一样,这使我能够拥有 5 个独立的导航堆栈,每个选项卡一个。对于屏幕表示,我使用的是 Android 片段,其中一些我试图在每个导航堆栈的不同位置重用。每个导航文件通常如下所示:
<fragment
android:id="@+id/gallery"
android:name="test.flows.socialNetwork.gallery.GalleryFragment"
android:label="@string/fotoghrafii"
tools:layout="@layout/fragment_gallery">
<action
android:id="@+id/action_gallery_to_countries"
app:destination="@id/countriesList" />
<action
android:id="@+id/action_gallery_to_profile"
app:destination="@id/galleryToInterlocutorProfile" />
</fragment>
<fragment
android:id="@+id/countriesList"
android:name="test.flows.common.countries.CountriesListFragment"
android:label="@string/vybor_strany"
tools:layout="@layout/fragment_select_country"/>
<navigation android:id="@+id/galleryToInterlocutorProfile"
app:startDestination="@id/galleryToInterlocutorProfile">
<fragment
android:id="@+id/galleryToInterlocutorProfile"
android:name="test.flows.socialNetwork.userProfile.UserProfileFragment"
android:label="galleryToInterlocutorProfile"
tools:layout="@layout/fragment_interlocutor_profile" />
</navigation>
我遇到的问题是导航中的所有片段都表现得像单例 - 如果我用数据填充一个用户界面,所有其他具有相同类的都在其他地方/导航堆栈(引用相同实例)中引用它并适当地更改。我想要的是重用具有相同 UI 但用于不同目的的片段 - 一个将显示应用程序用户数据,另一个 - 用户的朋友,另一个 - 另一个朋友等。所以,基本上我想要同一个片段的不同实例,而不是引用到整个应用程序中的同一个。它们的代码非常相似,所以我会为它们使用一个 **UserProfileFragment** 类以避免代码重复。如果您需要更多信息或说明,请告诉我,因为我不是全职 Android 开发人员,可能无法正确使用约定和术语。
提前致谢!
解决方案
因此,我找到了在代码中实现相同模式的“经典”方法,而不受每个片段有一个实例的限制。对于所有有兴趣在 Android 中实现全功能 iOS UITabBar 的人,这里有一个工作版本:https ://github.com/Codeveyor/Android-Tab-Bar
推荐阅读
- r - 将在 for 循环中创建的所有变量视为向量,例如 `c(x1,x2,x3,x4,x5,x6,x7,x8,x9,x10)`
- javascript - Material UI 的 Grid 组件 - 关闭行之间的垂直间隙
- jquery - 带有标签和内容的响应式指示线
- java - Jersey:尝试使用 jersey java 框架返回 XML 数据时出现 500 内部错误
- python - 跟踪对字典所做的更改
- performance - 这种排序算法的平均性能(大 O 表示法)是多少
- node.js - 通过子进程 exec 记录 typescript 编译器输出
- python - Visual Studio 2019 中的 conda 环境以及交互模式下的在线图形
- html - Angular 删除过滤表结果不更新显示 - Angular 模板驱动表单
- android - 如何在用户可以导航回活动的时间间隔后切换活动?