Navigation drawer: How do I set the selected item at startup?
AndroidNavigation DrawerAndroid Problem Overview
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.
Android Solutions
Solution 1 - Android
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.
Solution 2 - Android
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
Solution 3 - Android
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));
Solution 4 - Android
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
Solution 5 - Android
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
Solution 6 - Android
You can both highlight and select the item with the following 1-liner:
navigationView.getMenu().performIdentifierAction(R.id.posts, 0);
Solution 7 - Android
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:
- You have implemented
NavigationView.OnNavigationItemSelectedListener
in your activity - You have already called:
navigationView.setNavigationItemSelectedListener(this);
- The item you wish to select is located in position 0
Solution 8 - Android
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.
Solution 9 - Android
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));
Solution 10 - Android
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"
Solution 11 - Android
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));
Solution 12 - Android
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.
Solution 13 - Android
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"/>
Solution 14 - Android
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);
Solution 15 - Android
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));
Solution 16 - Android
you can do this,
nav_view.getMenu().findItem(R.id.menutem).setChecked(true)
Solution 17 - Android
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();
}
}
Solution 18 - Android
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"
/>
Solution 19 - Android
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);
}
Solution 20 - Android
For some reason it's preferable to find the MenuItem using the ID's.
drawer.getMenu().findItem(R.id.action_something).setChecked(true);