And*_*Dev 5 xml navigation android android-fragments
我正在使用jetpack导航在片段之间导航。
我有两个片段UserListFragment和ProfileFragment。在onViewCreated
调用服务器API的UserListFragment方法上,用户单击任何项将重定向到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" />
Run Code Online (Sandbox Code Playgroud)
所以我的问题是当用户向后按下第二个Fragment时如何防止呼叫onViewCreated
。
提前致谢
每当您从 ProfileFragment 再次访问 UserListFragment 时,OnViewCreated 方法都会调用,因为每当您要打开新的配置文件片段时,先前片段的视图都会被销毁。
对于您的任务,我认为您应该使用 LiveData 机制或管理您的列表数据条件,如果它有价值,则 API 不应调用。是 如果配置文件屏幕有任何更改,则通过通信进行界面。