0

Why addOnDestinationChangedListener not working, I want to know when the fragment change.

Error

Unable to start activity ComponentInfo{com.test/com.test.MainActivity}: java.lang.IllegalStateException: Activity com.test.MainActivity@7cc430 does not have a NavController set on 2131296700

activity_main.xml

<androidx.fragment.app.FragmentContainerView
        android:id="@+id/view_821"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:navGraph="@navigation/navigation_main" />

MainActivity.java

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityMainBinding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(activityMainBinding.getRoot());
        NavController navController = Navigation.findNavController(this, R.id.view_821);
        navController.addOnDestinationChangedListener((controller, destination, arguments) -> {
            Log.w("ABC", "A");
        });
    }
Taha Sami
  • 1,565
  • 1
  • 16
  • 43
  • Does this answer your question? [FragmentContainerView using findNavController](https://stackoverflow.com/questions/59275009/fragmentcontainerview-using-findnavcontroller) – Amin Jul 15 '21 at 06:55

2 Answers2

1

Error is that MainActivity does not have a NavController set

I don't think that is how you get access to the NavController in activity. Try this:

val navHostFragment =
        supportFragmentManager.findFragmentById(R.id.view_821) as NavHostFragment

navController = navHostFragment.findNavController()

Let me know if it fixed it for you :)

mehul bisht
  • 682
  • 5
  • 15
0

This worked with me

NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.view_821);
NavController navController = Objects.requireNonNull(navHostFragment).getNavController();
navController.addOnDestinationChangedListener((controller, destination, arguments) - > {

});
Taha Sami
  • 1,565
  • 1
  • 16
  • 43