Raghul Vaikundam
Raghul Vaikundam

Reputation: 588

How to close/finish the first activity when navigating from first activity to second activity using android navigation component

I have been using android navigation component for the first time and I am new to the Android architecture component as well. As far as I have seen, the navigation component in android architecture uses fragment predominantly for navigation within the same activity. I was trying to navigate from one activity to another using the navigation component:

activity.finish()              
Navigation.findNavController(btnView).navigate(R.id.activity)

Here R.id.activity is the id of the activity defined in the navigation graph XML file.

When I press the back button, I was still able to see the previous screen. My question is how the back stack works in the navigation component and why my first activity appears even though the destroy method of the activity is called (due to activity.finish()) ?

Upvotes: 2

Views: 5639

Answers (1)

Hussnain Haidar
Hussnain Haidar

Reputation: 2258

I can answer your second part for the first part someone will better understanding will explain you.

Your activity is not finished by executing this below method because if it was finished then you don't see it on back stack.

activity.finish()

finish current activity after navigate method. Below will be the correct way finishing current activity.

btn.setOnClickListener{            
Navigation.findNavController(btnView).navigate(R.id.secondActivity)
(activity as currentActivity).finish()
}

Upvotes: 4

Related Questions