I am using jetpack navigation to navigate between fragments.
I have two fragment UserListFragment and ProfileFragment.
On onViewCreated
method of UserListFragment called API of server and click of any item user will redirect to profileFragment.
If user press back from ProfileFragment, then it should come to userListFragment which is working. But onViewCreated
method calls again so API is calling again to take data from a server. I don't want to call onViewCreate
of first fragment. I want same behaviour as fragmentManager.add() not fragmentManager.replace().
Here is the code which I have written for navigating:
<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" />
So my question is to how can I prevent to call onViewCreated
when user presses back of the second Fragment.
Thanks in advance
Use Up or Back button to go to a previous step of the order flow.
There is nothing simpler, just extend/implement your BaseFragment class/interface and handle back-press events in onBackPressed() properly or just return false to ignore it. We are done!
Calling setRetainInstance(true) will prevent the Fragment from being re-created. But, right now the Activity is always re-creating the DrawerFragment and forcefully re-creating the HomeFragment , resulting in the behavior you are seeing. In your Activity. onCreate() check the savedInstanceState is null .
OnCreateView is called twice without pressing back button or on any other event. Its called twice, once when fragment initially creates and again just after findNavController. navigate event.
OnViewCreated method will call whenever you come again to UserListFragment from ProfileFragment because whenever you are going to open new profile fragment then previous fragment's view will be destroyed.
For your task, I think you should use LiveData mechanism or manage your List data condition based if it has value then API should not call. Yes If there are any changes from profile screen then Interface through communicate.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With