I have a navigationview with 2 groups, in one of the groups I add a new item programmatically using this example:
How to add an item to a menu group in NavigationView
How to create and get the id for the newly added item and set OnClickListener on him? (because I want to send some to to a database and get).
I want to create this behaviour:
the behaviour I want to create
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:showIn="navigation_view">
<group
android:id="#+id/group1"
android:checkableBehavior="single">
<item
android:id="#+id/nav_today"
android:icon="#drawable/ic_today"
android:orderInCategory="0"
android:title="#string/today" />
<item
android:id="#+id/nav_inbox"
android:icon="#drawable/ic_inbox"
android:orderInCategory="0"
android:title="#string/inbox_text" />
</group>
<group
android:id="#+id/group2"
android:checkableBehavior="none">
<item
android:id="#+id/nav_add_list"
android:icon="#drawable/ic_add"
android:orderInCategory="1"
android:title="#string/add_list_text" />
<item
android:id="#+id/nav_random_task"
android:icon="#drawable/ic_random_task"
android:orderInCategory="1"
android:title="#string/random_task" />
<item
android:id="#+id/nav_account"
android:icon="#drawable/ic_account"
android:orderInCategory="1"
android:title="#string/account" />
</group>
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme(R.style.BlueTheme);
setContentView(R.layout.activity_home_drawer);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TaskBottomSheet taskBottomSheet = new TaskBottomSheet();
taskBottomSheet.showNow(getSupportFragmentManager(), "taskBottomSheet");
}
});
drawer = 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 = findViewById(R.id.nav_view);
if (!TextUtils.isEmpty(listName)) {
addList(listName);
}
private void addList(String listName) {
Menu menu = navigationView.getMenu();
menu.add(R.id.group1, Menu.NONE, 0, listName).setIcon(R.drawable.ic_list);
}
I tried like this:
navigationView = findViewById(R.id.nav_view);
Menu menu = navigationView.getMenu();
final MenuItem menuItem = menu.add(R.id.group1, Menu.NONE, 0,"Read").setIcon(R.drawable.ic_list);
menuItem.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(HomeDrawerActivity.this, "Item clicked", Toast.LENGTH_SHORT).show();
menuItem.setCheckable(true);
if (drawer.isDrawerOpen(GravityCompat.START)){
drawer.closeDrawer(GravityCompat.START);
}
return true;
}
});
Another problem is the addList method. The newly menu added is not showed.Only when I add the menu directly after navigationView = findViewById the the item is showing.How to add multiple items and setOnClickListeners for them?
I am using navigation jetpack and have set up navigation drawer. Every thing works fine. But the problem is I want to show a toast when user clicks "nav_share" but it is not showing...
here is how i made navigation drawer
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_plan, R.id.navigation_notifications)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
my menu for navigation drawer is
<?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:showIn="navigation_view">
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_home"
android:icon="#drawable/ic_menu_camera"
android:title="#string/menu_home" />
<item
android:id="#+id/nav_gallery"
android:icon="#drawable/ic_menu_gallery"
android:title="#string/menu_gallery" />
<item
android:id="#+id/nav_slideshow"
android:icon="#drawable/ic_menu_slideshow"
android:title="#string/menu_slideshow" />
<item
android:id="#+id/nav_tools"
android:icon="#drawable/ic_menu_manage"
android:title="#string/menu_tools" />
</group>
<item android:title="Communicate">
<menu>
<item
android:id="#+id/nav_share"
android:icon="#drawable/ic_menu_share"
android:title="#string/menu_share" />
<item
android:id="#+id/nav_send"
android:icon="#drawable/ic_menu_send"
android:title="#string/menu_send" />
</menu>
</item>
</menu>
finally:
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
int id = menuItem.getItemId();
if (id == R.id.nav_share)
Toast.makeText(LauncherActivity.this, "Click", Toast.LENGTH_SHORT).show();
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
i want that click toast...i cannot see what am i missing....
if any one wants the answer..i did some research and finally found a solution to it...hope it helps....
NavigationView navigationView = findViewById(R.id.nav_view);
MenuItem shareItem = navigationView.getMenu().findItem(R.id.nav_share);
shareItem.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(LauncherActivity.this, "click", Toast.LENGTH_SHORT).show();
//do as you want with the button click
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
});
Use this
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.bringToFront()
navigationView.setNavigationItemSelectedListener(this);
I also had your problem and came up with the solution
NavController navController = Navigation.findNavController(this, R.id.nav_host_home);
NavigationUI.setupWithNavController(navigationView, navController);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
int id = menuItem.getItemId();
if (id == R.id.nav_share) {
Toast.makeText(getApplicationContext(), "nav_share", Toast.LENGTH_SHORT).show();
}
NavigationUI.onNavDestinationSelected(menuItem, navController);
drawerLayout.closeDrawer(Gravity.RIGHT);
return true;
}
});
In case if anyone is still searching for the answer as to how we can tie up navigation destinations and also handle click on menu items of the navigation drawer, it has been answered here: https://stackoverflow.com/a/57846680/3283350
Android Jetpack Navigation - Custom Action with Drawer Item
Simple step and easy
class MainActivity : AppCompatActivity(),NavigationView.OnNavigationItemSelectedListener{
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val navView: NavigationView = binding.navView
navController = findNavController(R.id.nav_host_fragment_content_main)
navView.setNavigationItemSelectedListener(this)
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
val url: String? = when (item.itemId) {
R.id.nav_privacy_policy -> MenuItemUrl.PRIVACY_POLICY
R.id.nav_term_condition -> MenuItemUrl.TERM_AND_CONDITION
R.id.nav_contact_us -> MenuItemUrl.CONTACT_US
R.id.nav_feedback -> MenuItemUrl.FEEDBACK
R.id.nav_help_support -> MenuItemUrl.HELP_AND_SUPPORT
R.id.nav_faq -> MenuItemUrl.FAQ
R.id.nav_about_us -> MenuItemUrl.ABOUT_US
else -> null
}
if (url != null) Methods.openBrowser(this#MainActivity, url) // Do anything here ex. show toast etc.
NavigationUI.onNavDestinationSelected(item, navController)
drawerLayout.closeDrawer(GravityCompat.START)
return true
}
}
I have a navigation menu which looks like this -
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/nav_home"
android:icon="#drawable/ic_home"
android:title="Home" />
<item
android:id="#+id/nav_logout"
android:icon="#drawable/ic_logout"
android:title="Logout" />
<item
android:id="#+id/choose_bus"
android:title="Choose a bus">
<menu>
<group
android:id="#+id/group_select_bus"
android:checkableBehavior="single">
<!--<item-->
<!--android:id="#+id/menu_option1"-->
<!--android:title="Bus 1" />-->
<!--<item-->
<!--android:id="#+id/menu_option2"-->
<!--android:title="Bus 2" />-->
</group>
</menu>
</item>
I want to add menu_option1 and menu_option2 dynamically from the activity. I tried this but nothing adding -
#Override
public boolean onNavigationItemSelected(MenuItem item) {
NavigationView navView = (NavigationView) findViewById(R.id.nav_view);
Menu menu = navView.getMenu();
MenuItem item1 = menu.getItem(2);
SubMenu subMenu = item1.getSubMenu();
subMenu.add("Bus 1");
subMenu.add("Bus 2");
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
Try some thing like this
Menu menu = navView.getMenu();
menu.add(R.id.group_select_bus,Menu.NONE,Menu.NONE,Youritem);
Try this:
MenuItem item = mNavigationView.getMenu().getItem(2);
item.getSubMenu().add(R.id.group_select_bus, id, Menu.NONE, "Youritem");
Another approach is to add all items in navigation menu and then change their visibility on specific activity or fragment, like
MenuItem item = mNavigationView.getMenu().getItem(5);
item.setVisible(false);
Seems a little late to answer. There is workaround/hack for this. No need to add list. Just add this little line above your code. It surely works.
override fun onNavigationItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.candidates -> {
binding.navSideView.post {
navSideView.menu.findItem(R.id.candidateManagement).isVisible = !navSideView.menu.findItem(R.id.candidateManagement).isVisible
}
}
}
return true
}
You need to add navigationview.post Runnable before changing visibility. It will update the menu. It works with group too. :)
I'm building an Android app for the local bus system and I'm trying to use the navigation drawer to act as a filter for the routes that appear on the map. The functionality is there, but I'm struggling with the UI. Whenever I click on an item, everything else is set as unchecked, which is not what I want. I've been trying to find a solution for this issue, but didn't come up with anything. Here is the code for the navigation drawer:
MainActivity:
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// listen for navigation events
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
// set up the hamburger icon to open and close the drawer
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.navigation_drawer_open,
R.string.navigation_drawer_close);
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
#Override
public boolean onNavigationItemSelected(final MenuItem menuItem) {
final boolean enable;
//update highlighted item in the navigation menu
//menuItem.setChecked(!menuItem.isChecked());
if(menuItem.isChecked()){
menuItem.setChecked(false);
enable = false;
}
else{
menuItem.setChecked(true);
enable=true;
}
//menuItem.setChecked(true);
mNavItemId = menuItem.getItemId();
// allow some time after closing the drawer before performing real navigation
// so the user can see what is happening
// mDrawerLayout.closeDrawer(GravityCompat.START);
mDrawerActionHandler.postDelayed(new Runnable() {
#Override
public void run() {
navigate(menuItem.getItemId(),enable);
}
}, DRAWER_CLOSE_DELAY_MS);
return true;
}
and the layout file:
<item
android:id="#+id/filter_routes"
android:title="#string/filter">
<menu>
<group android:checkableBehavior="all">
<item
android:id="#+id/red_route"
android:title="#string/red_route"
android:checkMark="?android:attr/listChoiceIndicatorMultiple"
android:icon="#drawable/abc_btn_check_material"
android:checked="true"
android:checkable="true"/>
<item
android:id="#+id/blue_route"
android:title="#string/blue_route"
android:icon="#drawable/abc_btn_check_material"
android:checkMark="?android:attr/listChoiceIndicatorMultiple"
android:checked="true"
android:checkable="true"/>
<item
android:id="#+id/green_route"
android:title="#string/green_route"
android:icon="#drawable/abc_btn_check_material"
android:checkMark="?android:attr/listChoiceIndicatorMultiple"
android:checked="true"
android:checkable="true"/>
<item
android:id="#+id/orange_route"
android:title="#string/orange_route"
android:icon="#drawable/abc_btn_check_material"
android:checkMark="?android:attr/listChoiceIndicatorMultiple"
android:checked="true"
android:checkable="true"/>
<item
android:id="#+id/brown_route"
android:title="#string/brown_route"
android:icon="#drawable/abc_btn_check_material"
android:checkMark="?android:attr/listChoiceIndicatorMultiple"
android:checked="true"
android:checkable="true"/>
</group>
</menu>
</item>
I got multiple selections to work by returning false from onNavigationItemSelected(). From the Google docs for this return value of onNavigationItemSelected():
boolean true to display the item as the selected item
Apparently, this means that returning false leaves item selection in your control.
Here's an example.
XML:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:title="All">
<menu>
<group
android:checkableBehavior="all"
android:id="#+id/checkable_group"
>
<item
android:id="#+id/checkable_item_1"
android:title="A" />
<item
android:id="#+id/checkable_item_2"
android:title="B" />
<item
android:id="#+id/checkable_item_3"
android:title="C" />
<item
android:id="#+id/checkable_item_4"
android:title="D" />
</group>
</menu>
</item>
</menu>
Code:
#Override
public boolean onNavigationItemSelected(MenuItem item) {
if (item.isChecked()) {
item.setChecked(false);
}
else {
item.setChecked(true);
}
return false; // VERY Important to return false here
}
I submitted a bug report about this and it was closed as working as intended. Google apparently made NavigationView use menu XML with no intention of having it work like a menu.
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.
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.
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
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));
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
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
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
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
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.
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));
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"
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));
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.
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"/>
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);
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));
you can do this,
nav_view.getMenu().findItem(R.id.menutem).setChecked(true)
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();
}
}
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"
/>
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);
}
For some reason it's preferable to find the MenuItem using the ID's.
drawer.getMenu().findItem(R.id.action_something).setChecked(true);