Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I disable back navigation and remove the back arrow on a Fragment, using Android Jetpack's Navigation component?

I am using Google's recommended single activity pattern with Android Jetpack's Navigation component.

Fragment 1 is an authentication screen. After the user is authenticated and navigates to Fragment 2, I would like to make pressing of the Android back button close the app, and remove the back arrow in the app bar.

I have found methods, like onBackPressedDispatcher, to add / remove functionality from the back press, but nothing that also removes the back arrow.

I have also tried app:popUpTo="@+id/firstFragment" when navigating from Fragment 1 to Fragment 2, but that doesn't work either.

This should be possible to specify with a single line of code. Still trying to find. Any tips?

like image 700
efa303 Avatar asked Oct 15 '25 07:10

efa303


1 Answers

You need to remove fragment1 from back-stack when navigation to fragment2

fragment1

<fragment
android:id="@+id/fragment1"
android:name="packagenameforFragment1"
android:label="fragment1"
tools:layout="@layout/fragment_1" >
<action
    android:id="@+id/action_Fragment1_to_Fragment2"
    app:destination="@id/Fragment2_id"
    app:launchSingleTop="true"
    app:popUpTo="@+id/your_MainGraph_id"
    app:popUpToInclusive="true" />

then when you navigate from fragment1 to fragment2 call this

findNavController(fragment).navigate(R.id.action_Fragment1_to_Fragment2)

to remove the back button from Fragment2 you can use this

in Activity onCreate()

val appBarConfiguration = AppBarConfiguration
        .Builder(R.id.your_fragment2_id,R.id.any_other_ids_you_want)
        .build()

then setup your toolbar like this

setupActionBarWithNavController(this, yourNavController, appBarConfiguration)
like image 194
Mohammed Alaa Avatar answered Oct 16 '25 22:10

Mohammed Alaa