How to fix Android studio 3.5 navigation activity template onNavigationItemSelected not working
this problem is caused by the ordering issue of xml file from main content
the default order:
<com.google.android.material.navigation.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="@layout/nav_header_main"
app:menu="@menu/activity_main_drawer" />
<include
layout="@layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
change to following order:
<include
layout="@layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<com.google.android.material.navigation.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="@layout/nav_header_main"
app:menu="@menu/activity_main_drawer" />
When you call NavigationUI.setupWithNavController(navigationView, navController)
, you're saying that you want NavController
to handle click events from your NavigationView, navigating to the related screen as per the NavigationUI documentation. This, by necessity, calls setNavigationItemSelectedListener()
internally, overriding the setNavigationItemSelectedListener()
you call earlier in onCreate()
. If you've hooked up your NavigationView
to fragments in your app (as the template does out of the box), then there is no need to call setNavigationItemSelectedListener
yourself.
Of course, you should ensure that your layout has not changed from what the Navigation Drawer Activity gives you by default - there is a known issue with Android Studio 3.5 that can lead to the order of views being changed which would break cases like DrawerLayout
(where the order of children matters greatly)