在回按片段时,禁止使用导航图调用上一个片段的onViewCreated

时间:2019-01-21 12:00:23

标签: android xml android-fragments navigation

我正在使用jetpack导航在片段之间导航。

我有两个片段 UserListFragment ProfileFragment 。 在称为服务器API的UserListFragment的onViewCreated方法上,用户单击任何项​​目都将重定向到profileFragment。

如果用户从ProfileFragment上按回,则应该进入正在工作的userListFragment。但是,onViewCreated方法再次调用,因此API再次调用以从服务器获取数据。我不想调用第一个片段的onViewCreate。我想要与fragmentManager.add()相同的行为,而不是fragmentManager.replace()。

这是我为导航而编写的代码:

<fragment
    android:id="@+id/navigationUserListFragment"
    android:name="packageName.dashboard.UserListFragment"
    android:label="fragment_userlist"
    tools:layout="@layout/fragment_user_list">

   <action
        android:id="@+id/actionToProfile"
        app:destination="@id/navigationProfile"
        app:launchSingleTop="true"
        app:popUpTo="@id/navigationUserListFragment" />
</fragment>


<fragment
    android:id="@+id/navigationProfile"
    android:name="package.dashboard.ProfileFragment"
    android:label="profile_fragment"
    tools:layout="@layout/fragment_profile" />

所以我的问题是当用户向后按下第二个片段时,如何防止呼叫onViewCreated

预先感谢

1 个答案:

答案 0 :(得分:2)

OnViewCreated方法将在您再次从ProfileFragment进入UserListFragment时调用,因为每当您要打开新的配置文件片段时,先前片段的视图都会被破坏。

对于您的任务,我认为您应该使用LiveData机制或基于List数据条件(如果它具有值)来管理,那么API不应调用。是,如果个人资料屏幕上有任何更改,则通过通讯进行界面。