Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android navigation architecture component - system's back button exits the app

I am making a demo using android's navigation architecture component. I have an activity and two fragments.

In the activity's xml, I have added the following code-

<fragment
    android:id="@+id/main_container"
    android:name="androidx.navigation.fragment.NavHostFragment"
    android:layout_width="@dimen/match_constraints"
    android:layout_height="@dimen/match_constraints"
    app:defaultNavHost="true"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:navGraph="@navigation/nav_graph" />

And then I have set the first fragment as the start destination. In the first fragment, on a button's click I have done following -

NavHostFragment.findNavController(this).navigate(R.id.action_firstFragment_to_secondFragment)

And it works fine. Now when I press system's back button, ideally I should go back to first fragment, but the app exits. What am I doing wrong?

like image 246
Himanshu Ganoliya Avatar asked Nov 26 '18 14:11

Himanshu Ganoliya


People also ask

What happens when back button is pressed in Android?

However, when the back button is pressed, the activity is destroyed, meaning, the temporary data is lost during this call. This is what the official documentation states. But we do not want to lose this data. To retain the data, we need to override the back pressed method.

Where is the back button on the Android navigation system?

The Back button appears in the system navigation bar at the bottom of the screen and is used to navigate in reverse-chronological order through the history of screens the user has recently worked with.

Do Android apps need a back button?

All Android devices provide a Back button for this type of navigation, so you should not add a Back button to your app's UI. Depending on the user's Android device, this button might be a physical button or a software button.

How do I navigate back on android?

You can go back more than once. But when you reach the Home screen, you can't go back any further. Gesture navigation: Swipe from the left or right edge of the screen. 2-button navigation: Tap Back .


1 Answers

I suppose, this is occurring in your code just because you might be handling the onBackPressed() functionality somewhere in your BaseActivity. Please look carefully.

I hope, this helps you.

like image 87
Nitin Gurbani Avatar answered Oct 23 '22 10:10

Nitin Gurbani