0

I am using Jetpack compose with one activity & multiple composable destinations.
Activity named is MainActiviy & Composable destinations are A->B->C
Suppose I am in C & I backpress, I need to know in onBackPressed() of mainActivity that now in backstack of navigation destinations 2 destinations are left.
Can anyone please help on this

  • You should not even be overriding onBackPressed at all, ever, as explained in the [Predictive Back guide](https://developer.android.com/guide/navigation/predictive-back-gesture). Navigation already handles the back button correctly for you by using the [Compose APIs specifically for handling system back](https://developer.android.com/jetpack/compose/libraries#handling_the_system_back_button). What makes you think you need to do anything with system back? – ianhanniballake Apr 02 '23 at 14:12
  • @ianhanniballake There is a case where if compose destination stack is empty & at activity level current activity is last activity then I want to take user to home activity. And from there if he presses back then app gets closed. Are you aware that this change on backPress it has to be compulsorily done when migrating to SDK 33 or can be done later as well before SDK 34 – Ujjwal Kumar Maharana Apr 04 '23 at 06:14

1 Answers1

0

Not really sure what you are looking for, but it might be useful to call addOnDestinationChangedListener in your fragment or activity.

You get notified when destinaton changes and get hold of the route and the navController. Maybe that solves your problem, IDK?

Something like this for fragment:

   @OptIn(ExperimentalAnimationApi::class)
  override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?,
  ): View {
    return ComposeView(requireContext()).apply {
      setContent {
        MyAppTheme {
          val navController = rememberAnimatedNavController()
          navController.addOnDestinationChangedListener { navController, destination, bundle ->
            if (destination.route == "A") doSomething()
            // navController.currentBackStackEntry)
          }
          AnimatedNavHost(
            navController = navController,
            startDestination = "A",
          ) {
            composable(
              route = "A",
              content = { ScreenAComposable() },
            )
            composable(
              route = "B",
              content = { ScreenBComposable() },
            )
            composable(
              route = "C",
              content = { ScreenCComposable() },
            )
          }
        }
      }
    }
  }