Navigation drawer: How do I set the selected item at startup?
Asked Answered
I

20

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.

Insomnia answered 5/7, 2015 at 17:51 Comment(2)
Does any of the answers trigger onNavigationItemSelected action for the selected id?Snowberry
@Snowberry yes, #31233779Ilonailonka
R
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.

Reproof answered 5/7, 2015 at 18:13 Comment(9)
Android Support Libraries v23 added setCheckedItem (int id).Freewheel
@MarkusRubey even after setting setCheckedItem I am unable to highlight the selected item. Could you tell the possible reason ?Parimutuel
Not worked for me! When method onNavigationItemSelected 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.Deadfall
Neither of mentioned methods worked for me for some reason. But doing navigationView.post(new Runnable() { navigationView.setCheckedItem(...) }) - worked.Trubow
You are probably trying to change the checked item from a different thread than the main thread :)Reproof
Adding the attribute android:checkable="true" for each item in the menu.xml worked for meBale
I am dynamically adding menu items to navigation drawer menu and menuItem.setCheckable(true) did the trick for me in addition to this answer.Paine
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.Overexcite
Does NOT trigger onNavigationItemSelected action for the selected idIlonailonka
T
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

Templia answered 3/9, 2015 at 12:26 Comment(5)
even after setting setCheckedItem I am unable to highlight the selected item. Could you tell the possible reason ?Parimutuel
@DeepeshDoshi Please make sure you have a checkable behavior.Gwynethgwynne
it should he navigationView.setCheckedItem(R.id.menu_nav_home) to select home menuCarlina
for individual Item just add android:checkable="true" else it won't be checked by self.Bale
Also make sure you don't call this method from with navItemSelecteListener as item is selected after this method returns.Conah
M
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));

Megan answered 16/10, 2015 at 13:9 Comment(3)
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.Marchese
onNavigationItemSelected(navView.getMenu().getItem(0)); or onNavigationItemSelected(navView.getMenu().getItem(R.id.nav_profile)); both worked for me, getitem instead of finditem.Kerseymere
But why does this method also not check the item if onNavigationItemSelected returns true?Morbid
D
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

Deadfall answered 4/11, 2015 at 11:47 Comment(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.Aquino
@McAdam331 Of course feel free, it is half gone by here today and did not have time to write in more detail.Deadfall
P
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

Polyglot answered 7/11, 2015 at 18:5 Comment(0)
C
17

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

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

Source: https://mcmap.net/q/119074/-how-to-select-the-first-item-in-a-navigation-drawer-and-open-a-fragment-on-application-start

Corpora answered 8/4, 2016 at 18:3 Comment(1)
This is the only answer that worked straightaway. Checks the option and opens the fragment. Great answer.Wickliffe
B
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
Builtup answered 15/7, 2016 at 0:52 Comment(0)
P
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.

Pulp answered 5/2, 2017 at 17:8 Comment(0)
C
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));

Cannabis answered 17/1, 2016 at 5:45 Comment(0)
S
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"

Send answered 15/5, 2018 at 6:27 Comment(2)
In my opinion best answer, cause uses default Android provided logic. Voted as best only is better, if menu is using layout and generated by adapter not menu xml file.Elviaelvie
This is the best answerJosefina
K
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));
Keble answered 15/11, 2016 at 10:3 Comment(0)
C
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.

Cowberry answered 15/5, 2019 at 7:24 Comment(0)
G
2

First of all create colors for selected item. Here https://mcmap.net/q/119075/-how-to-customize-item-background-and-item-text-color-inside-navigationview 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"/>
Goliard answered 15/10, 2015 at 12:20 Comment(2)
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.Aquino
I think perhaps you want menuItem.getItemId() instead of itemIdSatanic
S
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);
Spinster answered 10/8, 2019 at 8:7 Comment(0)
C
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));
Cryptogenic answered 24/10, 2017 at 13:43 Comment(1)
Can you please tell me how and where this onNavigationItemSelected is accessible? Please provide a fuller code example.Rao
T
1

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

Triumphant answered 8/1, 2020 at 7:23 Comment(0)
D
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();
    }
}
Diplostemonous answered 23/3, 2022 at 12:10 Comment(1)
You can delete the else statement, cause, in every case, you will do the super.onBackPress() method.Insomnia
V
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"
        />
Volkslied answered 2/11, 2017 at 9:8 Comment(0)
J
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);
    
     } 
Juster answered 30/5, 2021 at 22:39 Comment(0)
C
-1

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

drawer.getMenu().findItem(R.id.action_something).setChecked(true);
Centaurus answered 21/10, 2015 at 10:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.