如何跨导航堆栈重用 android 片段(iOS 标签栏在 Android 中的实现)?

How to reuse android fragment across navigation stacks (iOS Tab Bar implementation in Android)?

我正在构建一个 Android 应用程序来复制现有的 iOS 应用程序并且我正在使用 Bottom Navigation element as the core app structure which is similar to iOS Tab Bar pattern. So, I have one main Activity in the app which only handles bottom navigation. Currently, I have 5 tabs and I populate each tab with navigation with nested graphs precisely as in this official Android architecture example,这使我能够拥有 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,所有其他具有相同 class 的都在其他 places/navigation 堆栈中引用它(指的是同一实例)并适当更改。我想要的是重用具有相同 UI 但出于不同目的的片段 - 一个将显示应用程序用户数据,另一个 - 用户的朋友,另一个 - 另一个朋友等。所以,基本上我想要相同的不同实例片段,而不是在整个应用程序中引用同一个片段。它们的代码非常相似,所以我会为它们全部使用一个 **UserProfileFragment** class 以避免代码重复。如果您需要更多信息或说明,请告诉我,因为我不是全职 Android 开发人员,可能无法正确使用约定和术语。

提前致谢!

因此,我找到了在代码中实现相同模式的“经典”方法,而不受每个片段都有一个实例的限制。对于有兴趣在 Android 中实现全功能 iOS UITabBar 的每个人,一个工作版本在这里:https://github.com/Codeveyor/Android-Tab-Bar