Home > Back-end >  How can I back from the second fragment to the first fragment using Navigation Component?
How can I back from the second fragment to the first fragment using Navigation Component?

Time:03-06

How can I back from the second fragment to the first fragment using Navigation Component?

navigation_main.xml

<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@ id/main_navigation"
    app:startDestination="@id/firstFragment">

    <fragment
        android:id="@ id/firstFragment"
        android:name="com.test.ttt.FirstFragment"
        tools:layout="@layout/fragment_first">

        <action
            android:id="@ id/action_firstFragment_to_secondFragment"
            app:destination="@id/secondFragment"
            app:popUpTo="@id/firstFragment" 
            app:popUpToInclusive="true"/>

    </fragment>

    <fragment
        android:id="@ id/secondFragment"
        android:name="com.test.ttt.SecondFragment"
        tools:layout="@layout/fragment_second" />

</navigation>

FirstFragment.java

public class FirstFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Navigation.findNavController(container).navigate(FirstFragmentDirections.actionFirstFragmentToSecondFragment());
        return inflater.inflate(R.layout.fragment_first, container, false);
    }

}

I want when I press the back button in the second fragment, It must back to the first fragment but currently, When I press the back button in the second fragment it is leaving the app.

How can I solve this problem?

CodePudding user response:

The reason you are being exited from the app is because while navigating to the second fragment, you are removing the first fragment from your stack. The properties app:popUpTo and app:popUpToInclusive are typically used when you want to remove some fragments from your backstack while navigating. A simple use case for this would be when navigating from Login/SignUp Fragment to Home/Main Fragment. In this case you would not want the user to be able to press back and go back to login/signup screens. Here is where the two properties would help.

TL;DR - Remove the app:popUpTo and app:popUpToInclusive properties from your action

Change

    <action
        android:id="@ id/action_firstFragment_to_secondFragment"
        app:destination="@id/secondFragment"
        app:popUpTo="@id/firstFragment" 
        app:popUpToInclusive="true"/>

to

    <action
        android:id="@ id/action_firstFragment_to_secondFragment"
        app:destination="@id/secondFragment"/>
  • Related