244

My code works perfectly: every time an item in Navigation Drawer is clicked the item is selected.

Of course I want to start the app with a default fragment (home), but Navigation Drawer doesn't have the item selected. How can I select that item programmatically?

public class BaseApp extends AppCompatActivity {

    //Defining Variables
    protected String LOGTAG = "LOGDEBUG";
    protected Toolbar toolbar;
    protected NavigationView navigationView;
    protected DrawerLayout drawerLayout;

    private DateManager db = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.base_layout);

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


        // set the home/dashboard at startup

        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.frame, new DashboardFragment());
        fragmentTransaction.commit();

        setNavDrawer();
    }

    private void setNavDrawer(){

        // Initializing Toolbar and setting it as the actionbar
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        //Initializing NavigationView

        //Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {

            // This method will trigger on item Click of navigation menu
            @Override
            public boolean onNavigationItemSelected(MenuItem menuItem) {


                //Checking if the item is in checked state or not, if not make it in checked state

                // I THINK THAT I NEED EDIT HERE...

                if (menuItem.isChecked()) menuItem.setChecked(false);
                else menuItem.setChecked(true);

                //Closing drawer on item click
                drawerLayout.closeDrawers();


                //Check to see which item was being clicked and perform appropriate action
                switch (menuItem.getItemId()) {    

                    //Replacing the main content with ContentFragment 

                    case R.id.home:

                        DashboardFragment dashboardFragment = new DashboardFragment();
                        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
                        fragmentTransaction.replace(R.id.frame, dashboardFragment,"DASHBOARD_FRAGMENT");
                        fragmentTransaction.commit();
                        return true;
[...]

I think that I need to edit here:

if (menuItem.isChecked()) menuItem.setChecked(false);
                    else menuItem.setChecked(true);

Or in onCreate at App startup with FragmentTransaction.

Thank you for your support.

mmBs
  • 8,421
  • 6
  • 38
  • 46
sineverba
  • 5,059
  • 7
  • 39
  • 84
  • Does any of the answers trigger `onNavigationItemSelected` action for the selected id? – Prabs Feb 03 '17 at 11:14
  • @Prabs yes, https://stackoverflow.com/questions/31233279/navigation-drawer-how-do-i-set-the-selected-item-at-startup/33521048#33521048 – B-GangsteR Jul 16 '18 at 00:30

20 Answers20

512

Use the code below:

navigationView.getMenu().getItem(0).setChecked(true);

Call this method after you call setNavDrawer();

The getItem(int index) method gets the MenuItem then you can call the setChecked(true); on that MenuItem, all you are left to do is to find out which element index does the default have, and replace the 0 with that index.

You can select(highlight) the item by calling

onNavigationItemSelected(navigationView.getMenu().getItem(0));

Here is a reference link: http://thegeekyland.blogspot.com/2015/11/navigation-drawer-how-set-selected-item.html

EDIT Did not work on nexus 4, support library revision 24.0.0. I recommend use

navigationView.setCheckedItem(R.id.nav_item);

answered by @kingston below.

Muhammed Refaat
  • 8,914
  • 14
  • 83
  • 118
Arlind Hajredinaj
  • 8,380
  • 3
  • 30
  • 45
  • 68
    Android Support Libraries v23 added [`setCheckedItem (int id)`](https://developer.android.com/reference/android/support/design/widget/NavigationView.html#setCheckedItem(int)). – Markus Rubey Aug 21 '15 at 10:44
  • 1
    @MarkusRubey even after setting setCheckedItem I am unable to highlight the selected item. Could you tell the possible reason ? – Dexto Sep 30 '15 at 21:18
  • 3
    Not worked for me! When method [onNavigationItemSelected](https://developer.android.com/intl/pt-br/reference/android/support/design/widget/NavigationView.OnNavigationItemSelectedListener.html) is called for other options in navigation menu drawer, the initial item referred to as "checked" is maintaining their state always. When i use 'navigationView.setCheckedItem(id);' worked perfectly! After that it must call the method 'navigationView.getMenu () performIdentifierAction (R.id.nav_market, 0);' to perform the selection of the desired item. – GFPF Nov 04 '15 at 11:34
  • 4
    Neither of mentioned methods worked for me for some reason. But doing `navigationView.post(new Runnable() { navigationView.setCheckedItem(...) })` - worked. – dimsuz Apr 28 '16 at 11:27
  • 1
    You are probably trying to change the checked item from a different thread than the main thread :) – Arlind Hajredinaj Apr 28 '16 at 11:31
  • 1
    Adding the attribute `android:checkable="true"` for each item in the `menu.xml` worked for me – sud007 Jun 12 '17 at 09:52
  • I am dynamically adding menu items to navigation drawer menu and `menuItem.setCheckable(true)` did the trick for me in addition to this answer. – Madeyedexter Aug 24 '17 at 07:32
  • navigationView.getMenu().findItem(ResourceId).setChecked(true); for the ResourceId of the item will work if you don't want to rely on the index of the item. – steven smith Nov 04 '17 at 21:13
  • Does NOT trigger onNavigationItemSelected action for the selected id – B-GangsteR Jul 16 '18 at 00:31
118

You can also call:

navigationView.setCheckedItem(id);

This method was introduced in API 23.0.0

Example

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

    <group
        android:id="@+id/group"
        android:checkableBehavior="single">
        <item
            android:id="@+id/menu_nav_home"
            android:icon="@drawable/ic_home_black_24dp"
            android:title="@string/menu_nav_home" />
    </group>
</menu>

Note: android:checkableBehavior="single"

See also this

Jared Burrows
  • 54,294
  • 25
  • 151
  • 185
kingston
  • 11,053
  • 14
  • 62
  • 116
51

For me both these methods didn't work:

  • navigationView.getMenu().getItem(0).setChecked(true);
  • navigationView.setCheckedItem(id);

Try this one, it works for me.

onNavigationItemSelected(navigationView.getMenu().findItem(R.id.nav_profile));

Satan Pandeya
  • 3,747
  • 4
  • 27
  • 53
Raja Jawahar
  • 6,742
  • 9
  • 45
  • 56
  • 2
    Thanks for this tip. Above methods are actually ok, but problem different: if you use them, onNavigationItemSelected won't be called, only menu item will be checked. So we need to call both methods. – user1209216 Oct 30 '15 at 20:59
  • 2
    onNavigationItemSelected(navView.getMenu().getItem(0)); or onNavigationItemSelected(navView.getMenu().getItem(R.id.nav_profile)); both worked for me, getitem instead of finditem. – Harsh Dalwadi Feb 23 '17 at 08:55
  • But why does this method also not check the item if `onNavigationItemSelected` returns `true`? – Lorion Nov 30 '20 at 17:01
30

Example (NavigationView.OnNavigationItemSelectedListener):

private void setFirstItemNavigationView() {
        navigationView.setCheckedItem(R.id.custom_id);
        navigationView.getMenu().performIdentifierAction(R.id.custom_id, 0);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setFirstItemNavigationView();
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    FragmentManager fragmentManager = getFragmentManager();

    switch (item.getItemId()) {
        case R.id.custom_id:
            Fragment frag = new CustomFragment();

            // update the main content by replacing fragments
            fragmentManager.beginTransaction()
                    .replace(R.id.viewholder_container, frag)
                    .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
                    .addToBackStack(null)
                    .commit();
            break;
    }

Tks

GFPF
  • 959
  • 14
  • 19
  • 2
    This is one way to do it, I like it. Code-only answers are often discouraged, though. I would edit your answer to explain the code a little bit, such as why you use `performIdentifierAction` and what's happening in `onNavigationItemSelected`. To you it may seem straight forward, but a newer dev may have trouble understanding your code. – AdamMc331 Nov 04 '15 at 14:34
  • @McAdam331 Of course feel free, it is half gone by here today and did not have time to write in more detail. – GFPF Nov 04 '15 at 15:47
27

There are always problems with Googles "oh so great" support libs. If you want to check an item without downgrading your support libs version, just set checkable before setting checked state.

MenuItem item = drawer.getMenu().findItem(R.id.action_something);
item.setCheckable(true);
item.setChecked(true);

It might also work if you set checkable in the menu xml files

Daniel B
  • 1,205
  • 14
  • 18
16

You can both highlight and select the item with the following 1-liner:

navigationView.getMenu().performIdentifierAction(R.id.posts, 0);

Source: https://stackoverflow.com/a/31044917/383761

Community
  • 1
  • 1
Hugh Jeffner
  • 2,936
  • 4
  • 32
  • 31
9

API 23 provides the following method:

navigationView.setCheckedItem(R.id.nav_item_id);

However, for some reason this function did not cause the code behind the navigation item to run. The method certainly highlights the item in the navigation drawer, or 'checks' it, but it does not seem to call the OnNavigationItemSelectedListener resulting in a blank screen on start-up if your start-up screen depends on navigation drawer selections. It is possible to manually call the listener, but it seems hacky:

if (savedInstanceState == null) this.onNavigationItemSelected(navigationView.getMenu().getItem(0));

The above code assumes:

  1. You have implemented NavigationView.OnNavigationItemSelectedListener in your activity
  2. You have already called:
    navigationView.setNavigationItemSelectedListener(this);
  3. The item you wish to select is located in position 0
John P.
  • 4,358
  • 4
  • 35
  • 47
8

You have to call 2 functions for this:

First: for excuting the commands you have implemented in onNavigationItemSelected listener:

onNavigationItemSelected(navigationView.getMenu().getItem(R.id.nav_camera));

Second: for changing the state of the navigation drawer menu item to selected (or checked):

navigationView.setCheckedItem(R.id.nav_camera);

I called both functions and it worked for me.

MBH
  • 16,271
  • 19
  • 99
  • 149
6

Following code will only make menu item selected:

navigationView.setCheckedItem(id);

To select and open the menu item, add following code after the above line.

onNavigationItemSelected(navigationView.getMenu().getItem(0));

Satan Pandeya
  • 3,747
  • 4
  • 27
  • 53
Nikhil Misal
  • 93
  • 1
  • 5
5

Easiest way is to select it from xml as follows,

<menu>
   <group android:checkableBehavior="single">
         <item
              android:checked="true"
              android:id="@+id/nav_home"
              android:icon="@drawable/nav_home"
              android:title="@string/main_screen_title_home" />

Note the line android:checked="true"

Parinda Rajapaksha
  • 2,963
  • 1
  • 36
  • 40
4

This is my solution, very simple.

Here is my menu.xml file:

<group
    android:id="@+id/grp1"
    android:checkableBehavior="single">
    <item
        android:id="@+id/nav_all_deals"
        android:checked="true"
        android:icon="@drawable/ic_all_deals"
        android:title="@string/all_deals" />
    <item
        android:id="@+id/nav_news_and_events"
        android:icon="@drawable/ic_news"
        android:title="@string/news_and_events" />
    <item
        android:id="@+id/nav_histories"
        android:icon="@drawable/ic_histories"
        android:title="@string/histories" />
</group>

Above menu will highlight the first menu item. Below line will do something(eg: show the first fragment, etc). NOTE: write after 'configure your drawer code'

onNavigationItemSelected(mNavigationView.getMenu().getItem(0));
Na Pro
  • 715
  • 1
  • 8
  • 23
3

on your activity(behind the drawer):

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    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);
    navigationView.setCheckedItem(R.id.nav_portfolio);
    onNavigationItemSelected(navigationView.getMenu().getItem(0));
}

and

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

    Fragment fragment = null;

    if (id == R.id.nav_test1) {
        fragment = new Test1Fragment();
        displaySelectedFragment(fragment);
    } else if (id == R.id.nav_test2) {
        fragment = new Test2Fragment();
        displaySelectedFragment(fragment);
    }

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

and in your menu:

<group android:checkableBehavior="single">

    <item
        android:id="@+id/nav_test1"
        android:title="@string/test1" />

    <item
        android:id="@+id/nav_test2"
        android:title="@string/test2" />

  </group>

so first menu is highlight and show as default menu.

M.Namjo
  • 374
  • 2
  • 13
2

First of all create colors for selected item. Here https://stackoverflow.com/a/30594875/1462969 good example. It helps you to change color of icon. For changing background of all selected item add in your values\style.xml file this

  <item name="selectableItemBackground">@drawable/selectable_item_background</item>

Where selectable_item_background should be declared in drawable/selectable_item_background.xml

  <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/accent_translucent"
      android:state_pressed="true" />
    <item android:drawable="@android:color/transparent" />
   </selector>

Where color can be declared in style.xml

 <color name="accent_translucent">#80FFEB3B</color>

And after this

   // The main navigation menu with user-specific actions
        mainNavigationMenu_ = (NavigationView) findViewById(R.id.main_drawer);
        mainNavigationMenu_.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(MenuItem menuItem) {
                mainNavigationMenu_.getMenu().findItem(itemId).setChecked(true);
                return true;
            }
        });

As you see I used this mainNavigationMenu_.getMenu().findItem(itemId).setChecked(true); to set selected item. Here navigationView

 <android.support.design.widget.NavigationView
        android:id="@+id/main_drawer"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:headerLayout="@layout/header_main_navigation_menu"
        app:itemIconTint="@color/state_list"
        app:itemTextColor="@color/primary"
        app:menu="@menu/main_menu_drawer"/>
Community
  • 1
  • 1
Mikhail Valuyskiy
  • 1,238
  • 2
  • 16
  • 31
  • I like this method, I currently use it in my own project. It may help to include the `@color/state_list` code in your answer. Out of curiosity, where did you get the naming convention to put an underscore at the end of the variable name? I've never seen that approach. – AdamMc331 Nov 04 '15 at 14:37
  • I think perhaps you want `menuItem.getItemId()` instead of `itemId` – Craig Russell Nov 26 '15 at 13:54
2

When using BottomNavigationView the other answers such as navigationView.getMenu().getItem(0).setChecked(true); and navigationView.setCheckedItem(id); won't work calling setSelectedItemId works:

    BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation_view);

    bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
            // TODO: 10-Aug-19 your code here 
        }
    });

    bottomNavigationView.setSelectedItemId(R.id.myitem);
Roshna Omer
  • 687
  • 1
  • 11
  • 20
1

Below code is used to selected the first item and highlight the selected first item in the menu.

onNavigationItemSelected(mNavigationView.getMenu().getItem(0).setChecked(true));
Anbuselvan Rocky
  • 606
  • 6
  • 22
  • Can you please tell me how and where this onNavigationItemSelected is accessible? Please provide a fuller code example. – kilokahn Sep 18 '18 at 23:13
1

you can do this, nav_view.getMenu().findItem(R.id.menutem).setChecked(true)

1
    package com.example.projectdesign;
    import androidx.annotation.NonNull;
    import androidx.appcompat.app.ActionBarDrawerToggle;
    import androidx.appcompat.app.AppCompatActivity;
    import androidx.core.view.GravityCompat;
    import androidx.drawerlayout.widget.DrawerLayout;
    import androidx.fragment.app.Fragment;
         import android.annotation.SuppressLint;
      import android.app.Activity;
     import android.content.Intent;
     import android.os.Bundle;
     import android.view.MenuItem;
    import android.widget.Toast;

    import com.google.android.material.navigation.NavigationView;

    public class MenuDrawer extends AppCompatActivity implements 
    NavigationView.OnNavigationItemSelectedListener{
    public DrawerLayout drawerLayout;
    public ActionBarDrawerToggle actionBarDrawerToggle;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_menu_drawer);

        drawerLayout = findViewById(R.id.my_drwaer_layout);
        actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, 
      R.string.nav_open, R.string.nav_close);
        drawerLayout.addDrawerListener(actionBarDrawerToggle);
        actionBarDrawerToggle.syncState();
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        NavigationView navigationView = findViewById(R.id. nav_view ) ;
        navigationView.setNavigationItemSelectedListener( this ) ;
    }
    @SuppressLint("ResourceType")
    @SuppressWarnings ( "StatementWithEmptyBody" )
     @Override
    public boolean onNavigationItemSelected (MenuItem item){
        int id=item.getItemId();
        switch (id){
            case R.id.nav_account:
                Intent intent= new Intent(MenuDrawer.this, UsingBackKey.class);
                startActivity(intent);
                break;
            case R.id.women:
     
     
    getSupportFragmentManager().beginTransaction().replace(R.id.my_drwaer_layout,new 
    Fragment2()).commit();
                break;
            case R.id.men:
                Toast.makeText(getApplicationContext(),"Soon", 
   Toast.LENGTH_SHORT).show();
                break;
            case R.id.kids:
              Toast.makeText(getApplicationContext(),"Welcome to Kids", 
      Toast.LENGTH_SHORT).show();
                break;
        }
        drawerLayout.closeDrawer(GravityCompat.START);
        return super.onContextItemSelected(item);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {


        if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }

        return super.onOptionsItemSelected(item);

    }

    @Override
    public void onBackPressed() {
        if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
            drawerLayout.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
        super.onBackPressed();
    }
}
  • 1
    You can delete the `else` statement, cause, in every case, you will do the `super.onBackPress()` method. – sineverba Mar 24 '22 at 07:53
0

Make a selector for Individaual item of Nav Drawer

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/darkBlue" android:state_pressed="true"/>
    <item android:drawable="@color/darkBlue" android:state_checked="true"/>
    <item android:drawable="@color/textBlue" />
</selector>

Make a few changes in your NavigationView

<android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:itemBackground="@drawable/drawer_item"
        android:background="@color/textBlue"
        app:itemIconTint="@color/white"
        app:itemTextColor="@color/white"
        app:menu="@menu/activity_main_drawer"
        />
Ritesh
  • 876
  • 9
  • 14
0
bottomNavigationView.setSelectedItemId(R.id.menuItem);

Above worked for me, but I had place it inside onResume() method. Placing inside onNavigationItemSelected(@NonNull MenuItem item) caused me problems while switching back and forth between activities

   private BottomNavigationView bottomNavigationView;
    
     @Override
        public void onResume(){
            super.onResume();
            bottomNavigationView.setSelectedItemId(R.id.menuItem);
    
     } 
Balu mallisetty
  • 603
  • 9
  • 19
-1

For some reason it's preferable to find the MenuItem using the ID's.

drawer.getMenu().findItem(R.id.action_something).setChecked(true);
Enzokie
  • 7,365
  • 6
  • 33
  • 39