onNavigationItemSelected not working in NavigationView
Asked Answered
D

8

12

Please can someone help me with fragments from the navigation drawer, for some reason I can't get them to work and all the code looks right.

Here is the link to the source code.

Deterioration answered 10/9, 2016 at 8:46 Comment(3)
Please explain the problem you are having. Saying "not working" is too broad.Fake
What is the issue?Sos
If you download and open up the android project you'll notice that its has a navigation drawer which I'd like to use properly, so for example I'd like to click on The Wetlands which in turn should change the current fragment to the fragment_the_wetlands I've just got a dummy clock there for now to see whether or not the fragment is changing. I can't seem to get this right please help with that.Deterioration
S
17

Have a look at your MainActivity.java.

You have implemented the callbacks for NavigationView.OnNavigationItemSelectedListener in MainActivity as below,

@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
    // blah blah
}

Also check the setupDrawerContent method.

private void setupDrawerContent(NavigationView navigationView) {
    navigationView.setNavigationItemSelectedListener(
            new NavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(MenuItem menuItem) {
                    menuItem.setChecked(true);
                    drawerLayout.closeDrawers();
                    return true;
                }
            });
}

In this method you are creating a local OnNavigationItemSelectedListener.

So you are not using the OnNavigationItemSelectedListener that you have overridden in MainActivity.

The solution is to use this as argument for setNavigationItemSelectedListener. By doing this all your clicks will go the onNavigationItemSelected of MainActivity rather than going to the local onNavigationItemSelected.

private void setupDrawerContent(NavigationView navigationView) {
    navigationView.setNavigationItemSelectedListener(this);
}

Also move the code in the local onNavigationItemSelected to the onNavigationItemSelected of MainActivity.

So your onNavigationItemSelected will be something like this,

@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
    // Handle navigation view item clicks here.
    int id = menuItem.getItemId();
    menuItem.setChecked(true);
    drawerLayout.closeDrawers();

    if (id == R.id.nav_home) {
        // Handle the home action
        Toast.makeText(this, "Home", Toast.LENGTH_SHORT).show();
    } else if (id == R.id.nav_the_wetlands) {
        Toast.makeText(this, "The Wetlands", Toast.LENGTH_SHORT).show();
        TheWetlandsFragment theWetlandsFragment = new TheWetlandsFragment();
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.relativelayout_for_fragment, theWetlandsFragment, theWetlandsFragment.getTag()).commit();
    } else if (id == R.id.nav_the_mistbelt_forests) {
        Toast.makeText(this, "The Mistbelt Forests", Toast.LENGTH_SHORT).show();
    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

Also change your activity_main_drawer_view.xml as follows to solve the multiple selection issue you have in the Navigation Drawer,

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <group android:checkableBehavior="single">
        <item
            android:id="@+id/nav_home"
            android:icon="@drawable/ic_dashboard"
            android:title="Home" />
    </group>

    <item android:title="Information">
        <group android:checkableBehavior="single">
            <item
                android:id="@+id/nav_the_wetlands"
                android:icon="@drawable/ic_event"
                android:title="The Wetlands" />
            <item
                android:id="@+id/nav_the_mistbelt_forests"
                android:icon="@drawable/ic_event"
                android:title="The Mistbelt Forests" />
            <item
                android:id="@+id/nav_the_grasslands"
                android:icon="@drawable/ic_event"
                android:title="The Grasslands" />
        </group>
    </item>

    <item android:title="Quick Go To">
        <group android:checkableBehavior="single">
            <item
                android:id="@+id/nav_accommodation"
                android:icon="@drawable/ic_event"
                android:title="Accommodation" />
            <item
                android:id="@+id/nav_cuisine"
                android:icon="@drawable/ic_forum"
                android:title="Cuisine" />
            <item
                android:id="@+id/nav_leisure_activites"
                android:icon="@drawable/ic_forum"
                android:title="Leisure &amp; Activites" />
            <item
                android:id="@+id/nav_agri_tourism"
                android:icon="@drawable/ic_forum"
                android:title="Agri-tourism" />
            <item
                android:id="@+id/nav_education"
                android:icon="@drawable/ic_forum"
                android:title="Education" />
            <item
                android:id="@+id/nav_arts_crafts_decor"
                android:icon="@drawable/ic_forum"
                android:title="Arts, Crafts &amp; DeCor" />
            <item
                android:id="@+id/nav_selective_shopping"
                android:icon="@drawable/ic_forum"
                android:title="Selective Shopping" />
            <item
                android:id="@+id/nav_for_children"
                android:icon="@drawable/ic_forum"
                android:title="For Children" />
        </group>
    </item>

    <item android:title="Midlands Animals">
        <group android:checkableBehavior="single">
            <item
                android:id="@+id/nav_midlands_birding_checklist"
                android:icon="@drawable/ic_dashboard"
                android:title="Midlands Birding Checklist" />
            <item
                android:id="@+id/nav_midlands_mammals_checklist"
                android:icon="@drawable/ic_dashboard"
                android:title="Midlands Mammals Checklist" />
        </group>
    </item>

</menu>

Good luck.

Sos answered 12/9, 2016 at 9:36 Comment(0)
K
40

Use this code:

navigationView = (NavigationView) findViewById(R.id.navigationView); 
navigationView.bringToFront();
Kloster answered 12/9, 2017 at 22:4 Comment(4)
This helped me... thannks a lot !!Helenahelene
Wow, I just do not understand why this worked...but it worked.Janitor
With databinding .bringToFront() solved the issue. So: _binding.navView.setNavigationItemSelectedListener(this) - not enough. Then add _binding.navView.bringToFront() - and the listener is triggered.China
Thank you, 4 days without solution and the answer was here: navigationView.bringToFront(); Thanks a lot!Scottiescottish
S
17

Have a look at your MainActivity.java.

You have implemented the callbacks for NavigationView.OnNavigationItemSelectedListener in MainActivity as below,

@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
    // blah blah
}

Also check the setupDrawerContent method.

private void setupDrawerContent(NavigationView navigationView) {
    navigationView.setNavigationItemSelectedListener(
            new NavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(MenuItem menuItem) {
                    menuItem.setChecked(true);
                    drawerLayout.closeDrawers();
                    return true;
                }
            });
}

In this method you are creating a local OnNavigationItemSelectedListener.

So you are not using the OnNavigationItemSelectedListener that you have overridden in MainActivity.

The solution is to use this as argument for setNavigationItemSelectedListener. By doing this all your clicks will go the onNavigationItemSelected of MainActivity rather than going to the local onNavigationItemSelected.

private void setupDrawerContent(NavigationView navigationView) {
    navigationView.setNavigationItemSelectedListener(this);
}

Also move the code in the local onNavigationItemSelected to the onNavigationItemSelected of MainActivity.

So your onNavigationItemSelected will be something like this,

@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
    // Handle navigation view item clicks here.
    int id = menuItem.getItemId();
    menuItem.setChecked(true);
    drawerLayout.closeDrawers();

    if (id == R.id.nav_home) {
        // Handle the home action
        Toast.makeText(this, "Home", Toast.LENGTH_SHORT).show();
    } else if (id == R.id.nav_the_wetlands) {
        Toast.makeText(this, "The Wetlands", Toast.LENGTH_SHORT).show();
        TheWetlandsFragment theWetlandsFragment = new TheWetlandsFragment();
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.relativelayout_for_fragment, theWetlandsFragment, theWetlandsFragment.getTag()).commit();
    } else if (id == R.id.nav_the_mistbelt_forests) {
        Toast.makeText(this, "The Mistbelt Forests", Toast.LENGTH_SHORT).show();
    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

Also change your activity_main_drawer_view.xml as follows to solve the multiple selection issue you have in the Navigation Drawer,

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <group android:checkableBehavior="single">
        <item
            android:id="@+id/nav_home"
            android:icon="@drawable/ic_dashboard"
            android:title="Home" />
    </group>

    <item android:title="Information">
        <group android:checkableBehavior="single">
            <item
                android:id="@+id/nav_the_wetlands"
                android:icon="@drawable/ic_event"
                android:title="The Wetlands" />
            <item
                android:id="@+id/nav_the_mistbelt_forests"
                android:icon="@drawable/ic_event"
                android:title="The Mistbelt Forests" />
            <item
                android:id="@+id/nav_the_grasslands"
                android:icon="@drawable/ic_event"
                android:title="The Grasslands" />
        </group>
    </item>

    <item android:title="Quick Go To">
        <group android:checkableBehavior="single">
            <item
                android:id="@+id/nav_accommodation"
                android:icon="@drawable/ic_event"
                android:title="Accommodation" />
            <item
                android:id="@+id/nav_cuisine"
                android:icon="@drawable/ic_forum"
                android:title="Cuisine" />
            <item
                android:id="@+id/nav_leisure_activites"
                android:icon="@drawable/ic_forum"
                android:title="Leisure &amp; Activites" />
            <item
                android:id="@+id/nav_agri_tourism"
                android:icon="@drawable/ic_forum"
                android:title="Agri-tourism" />
            <item
                android:id="@+id/nav_education"
                android:icon="@drawable/ic_forum"
                android:title="Education" />
            <item
                android:id="@+id/nav_arts_crafts_decor"
                android:icon="@drawable/ic_forum"
                android:title="Arts, Crafts &amp; DeCor" />
            <item
                android:id="@+id/nav_selective_shopping"
                android:icon="@drawable/ic_forum"
                android:title="Selective Shopping" />
            <item
                android:id="@+id/nav_for_children"
                android:icon="@drawable/ic_forum"
                android:title="For Children" />
        </group>
    </item>

    <item android:title="Midlands Animals">
        <group android:checkableBehavior="single">
            <item
                android:id="@+id/nav_midlands_birding_checklist"
                android:icon="@drawable/ic_dashboard"
                android:title="Midlands Birding Checklist" />
            <item
                android:id="@+id/nav_midlands_mammals_checklist"
                android:icon="@drawable/ic_dashboard"
                android:title="Midlands Mammals Checklist" />
        </group>
    </item>

</menu>

Good luck.

Sos answered 12/9, 2016 at 9:36 Comment(0)
T
7

Don't use

NavigationUI.setupWithNavController(navigationView, navController);

instead of it do this

navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                Toast.makeText(MainActivity.this, "clicked", Toast.LENGTH_SHORT).show();
                return false;
            }
        });
Taxpayer answered 12/7, 2020 at 10:5 Comment(2)
This Answer is truly a life saverCandless
For those following this official tutorial, this is the solution you want.Sculpturesque
C
6

I have also faced the same problem some time back, and at the end i realized that i have not wrote the 2nd line of the following code

navigationView = (NavigationView) findViewById(R.id.navigation_view);        
navigationView.setNavigationItemSelectedListener(this);

you make sure you have written the same otherwise your listener will not work

Complicated answered 7/2, 2017 at 19:56 Comment(0)
C
1

in my case i forgot to initialize navigation menu.

kindly follow following code:

public void initSideMenu() {

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
}

happy coding...

Confirmed answered 15/9, 2019 at 18:44 Comment(0)
E
1

Make sure you have implement the interface NavigationView.OnNavigationItemSelectedListener. Second point make sure to add these lines otherwise listnere will not be called.

navigationView=(NavigationView) findviewbyid(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(this);
Encephalomyelitis answered 18/11, 2019 at 13:2 Comment(0)
B
1

This solved the issue for me->

Before, the NavigationView element was above the other elements

    <?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:nextFocusRight="@+id/recyclerview"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <FrameLayout
        android:id="@+id/toolbar_container"
        android:layout_width="match_parent"

        android:layout_height="wrap_content">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            app:elevation="0dp"
            android:nextFocusLeft="@+id/nav_view"
            android:layout_width="match_parent"
            android:touchscreenBlocksFocus="false"
            android:layout_height="?attr/actionBarSize"/>

    </FrameLayout>

    <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:background="@color/drawer_color"
        app:headerLayout="@layout/nav_header"
        app:menu="@menu/nav_menu"
        app:itemIconTint="@color/white"
        app:itemTextColor="@color/white"/>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        ...
    </ScrollView>
</androidx.drawerlayout.widget.DrawerLayout>

After I move the NavigationView to the bottom, the issue was solved :)

    <?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:nextFocusRight="@+id/recyclerview"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        ...
    </ScrollView>

    <FrameLayout
        android:id="@+id/toolbar_container"
        android:layout_width="match_parent"

        android:layout_height="wrap_content">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            app:elevation="0dp"
            android:nextFocusLeft="@+id/nav_view"
            android:layout_width="match_parent"
            android:touchscreenBlocksFocus="false"
            android:layout_height="?attr/actionBarSize"/>

    </FrameLayout>

    <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:background="@color/drawer_color"
        app:headerLayout="@layout/nav_header"
        app:menu="@menu/nav_menu"
        app:itemIconTint="@color/white"
        app:itemTextColor="@color/white"/>
</androidx.drawerlayout.widget.DrawerLayout>
Boff answered 24/2, 2024 at 7:33 Comment(1)
Thanks. I never imagined this was the issue.Teresiateresina
R
0

Add this line
navigationView.bringToFront(); Its works for me

Rhyne answered 7/6, 2021 at 7:49 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.