I have a problem with dynamically (programmatically) created submenu in navigation drawer when rotating the menu. My navigation view menu xml contains only main menu (see below). Submenu is added when onCreate event is called. Everything works fine until I rotate the screen - the only displayed thing from a submenu is its label. I tried to investigate the problem and also tried with static variables, but with no success.
Can you tell me what's wrong with my code?
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single" android:id="#+id/main_group">
<item
android:id="#+id/leagues_in_progress_item"
android:icon="#drawable/ic_format_line_spacing_black_48dp"
android:title="#string/title_activity_leagues_in_progress" />
<item
android:id="#+id/last_matches_item"
android:icon="#drawable/ic_access_alarm_black_48dp"
android:title="#string/title_activity_last_matches" />
<item
android:id="#+id/archive_item"
android:icon="#drawable/ic_folder_open_black_48dp"
android:title="#string/title_activity_archive" />
<item
android:id="#+id/put_score_item"
android:icon="#drawable/ic_add_circle_outline_black_48dp"
android:title="#string/title_activity_put_score" />
</group>
</menu>
HomeActivity.java:
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.pinokio);
this.mDrawerLayout = (DrawerLayout) findViewById(R.id.pinokioLayout);
// enabling action bar app icon and behaving it as toggle button
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
this.mDrawerToggle = new ActionBarDrawerToggle(this, this.mDrawerLayout, R.string.app_name, R.string.app_name);
this.mDrawerLayout.setDrawerListener(this.mDrawerToggle);
HomeActivity.mNavigationView = (NavigationView) findViewById(R.id.left_drawer);
this.addLeaguesSubmenu();
HomeActivity.mNavigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
displayMenuFragment(menuItem);
return true;
}
});
if (savedInstanceState == null) {
this.displayMenuFragment(HomeActivity.mNavigationView.getMenu().getItem(0));
}
}
/**
* Add submenu that contains leagues in progress
* #return HomeActivity
*/
private void addLeaguesSubmenu()
{
if (this.internetConnection.isOnline()) {
if (HomeActivity.menuLeagues == null) {
Intent intent = this.getIntent();
HomeActivity.menuLeagues = intent.getParcelableArrayListExtra("leagues");
}
this.leaguesSubmenu.generate(HomeActivity.mNavigationView, HomeActivity.menuLeagues);
}
}
And that's the method generating a submenu:
#Override
public void generate(NavigationView navigationView, ArrayList<League> leagues)
{
Menu menu = navigationView.getMenu();
SubMenu leaguesSubMenu = menu.addSubMenu(this.context.getResources().getString(R.string.title_activity_leagues_in_progress));
League league;
MenuItem menuItem;
for (int i = 0; i<leagues.size(); i++) {
league = leagues.get(i);
menuItem = leaguesSubMenu.add(league.getShortName());
Intent intent = new Intent();
intent.putExtra("leagueId", league.getId());
menuItem.setIntent(intent);
if (!league.getFoosballMode()) {
menuItem.setIcon(R.drawable.ic_fifa);
}
else {
menuItem.setIcon(R.drawable.ic_foosball);
}
}
}
I believe this is probably because when rotated the View gets reinflated but your generation code is in onCreate, so you have two options if thats the case. You can re-generate the menu when the view gets reinflated or add this to your Activity in your AndroidManifest.xml file:
android:configChanges="orientation|screenSize"
Also if your interesting refer to here for information on handling configuration changes such as rotation: http://developer.android.com/guide/topics/resources/runtime-changes.html
Related
I have only one user setting in my app, and I want to put it into the navigation drawer with a switch added to the given menu item.
Here is the relevant menu code:
<item
android:id="#+id/nav_dark"
android:checkable="true"
android:icon="#drawable/round_brightness_4_24"
android:title="#string/menu_dark"
app:actionViewClass="android.widget.Switch" />
The switch does appear on the right side of the menu item.
My listener:
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
if (item.getItemId() == R.id.nav_dark) {
// code to apply dark or light theme
// works as expected
}
else {
// code to handle regular menu items
// it works too
}
return true;
}
My problems:
When I tap on R.id.nav_dark the item gets selected. I would like the colored overlay to stay on (or jump back to) the previous menu item, whose fragment is actually shown behind the drawer.
The switch does not react accordingly, even if I use item.setChecked(true) manually. I would like the switch to be turned on when the dark theme is enabled and turned off when it's disabled.
Tapping on the switch itself does not pass the event to the menu item. I would like them to work in sync.
I have seen checkboxes and swiches working like this in other applications, although, most of them were in the app bar's overflow menu. (I have tried mine with a checkbox too, but no difference.)
I solved this problem using this thread: Switch in Navigation drawer item with Design Support Library on Android
In this example the dedicated menu item switches between a light and dark theme, but you can use it to toggle any settings, of course.
Problems to solve
Implement our own onNavigationItemSelected listener, because the default solution created by Android Studio prevents the use of a dedicated menu item.
Implement the fragment transaction and toolbar handling logic.
Implement the onCheckedChange listener of the switch.
What we do is capture clicks on the menu items. If it's a regular item, we change the fragment behind the drawer. If it's the dedicated item with the switch, we manually toggle the switch, which calls its listener.
The actual code (changing the theme in this case) is handled by the listener of the switch. If you click on the switch itself, the listener will be called directly.
Relevant code from activity_main_drawer.xml menu file
<item
android:id="#+id/nav_dark"
android:checkable="true"
android:icon="#drawable/round_brightness_4_24"
android:title="#string/menu_dark"
app:actionViewClass="android.widget.Switch" /> <!-- you can also use a CheckBox -->
Relevant code from MainActivity.java
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, Switch.OnCheckedChangeListener {
private Toolbar toolbar;
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle toggle;
private NavigationView navigationView;
private Switch switchDark;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = findViewById(R.id.toolbar);
toolbar.setTitle(getResources().getString(R.string.toolbar_title));
setSupportActionBar(toolbar);
// We have to handle the fragment changes manually,
// because what we do conflicts with the default solution created by Android Studio
drawerLayout = findViewById(R.id.drawer_layout);
toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawerLayout.addDrawerListener(toggle);
toggle.setDrawerIndicatorEnabled(true);
toggle.syncState();
navigationView = findViewById(R.id.nav_view);
// Check the menu item connected to the default fragment manually
navigationView.getMenu().findItem(R.id.nav_item1).setChecked(true);
navigationView.setNavigationItemSelectedListener(this); // See below!
switchDark = (Switch)navigationView.getMenu().findItem(R.id.nav_dark).getActionView();
// Set the default state of the switch connected to the menu item
switchDark.setChecked(AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES);
switchDark.setOnCheckedChangeListener(this); // See below!
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
// Handle the menu item with the switch
if (item.getItemId() == R.id.nav_dark) {
((Switch)item.getActionView()).toggle(); // Call the onCheckedChangeListener of the switch and let it do the work
return false; // Prevent the menu item to get selected (No overlay indicator will appear)
}
// Handle the other menu items
// We have to do this, because we deleted the default solution created by Android Studio
Fragment newFragment = null;
if (item.getItemId() == R.id.nav_item1) {
newFragment = new CustomFragment();
toolbar.setTitle(getResources().getString(R.string.custom_fragment_title));
}
else if (item.getItemId() == R.id.nav_item2) {
newFragment = new OtherFragment();
toolbar.setTitle(getResources().getString(R.string.other_fragment_title));
}
// Start the fragment transition manually
if (newFragment != null) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.nav_host_fragment, newFragment);
transaction.addToBackStack(null);
transaction.commit();
drawerLayout.close();
}
return true; // The selected item will have the overlay indicator
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(buttonView.getContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
int themeID;
if (isChecked) {
themeID = AppCompatDelegate.MODE_NIGHT_YES;
}
else {
themeID = AppCompatDelegate.MODE_NIGHT_NO;
}
AppCompatDelegate.setDefaultNightMode(themeID); // Change the theme at runtime
editor.putInt("themeID", themeID); // Save it to be remembered at next launch
editor.apply();
}
}
try this one.
<item
app:actionViewClass="androidx.appcompat.widget.SwitchCompat"
android:icon="#drawable/message"
android:title="All inboxes"
android:id="#+id/inbox"
/>
this above is the menu item we need
in order to get click events follow below steps mentioned
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
if (item.getItemId()==R.id.inbox){
((SwitchCompat) item.getActionView()).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){
Toast.makeText(buttonView.getContext(), "Checked", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(buttonView.getContext(), "unChecked", Toast.LENGTH_SHORT).show();
}
}
});
}
Toast.makeText(MainActivity.this, ""+item.getTitle(), Toast.LENGTH_SHORT).show();
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
});
we already given our action class in menu item from xml .
we just need to verify which item it was and when it happens we can get the actionviewclass that we had assigned
and an onclicklistener on it .. this one worked for me .
I am trying to implement Sidebar NavigationDrawer in my Android project.
To do so, I have used NavigationView in DrawerLayout. To show items I used menu.
I want to add click event on that added menu items.
Code for reference:
In navigation menu -
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/nav_account" android:title="My Account"/>
<item android:id="#+id/nav_settings" android:title="Settings"/>
<item android:id="#+id/nav_layout" android:title="Log Out"/>
</menu>
In View:
<android.support.design.widget.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:menu="#menu/navigation_menu"
android:layout_gravity="start" />
Implement the listener in your Activity:
public class HomeActivity extends AppCompatActivity implements
NavigationView.OnNavigationItemSelectedListener
setNavigationItemSelectedListener in onCreate of Activity
NavigationView mNavigationView = (NavigationView) findViewById(R.id.account_navigation_view);
if (mNavigationView != null) {
mNavigationView.setNavigationItemSelectedListener(this);
}
Override the method
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_account) {
// DO your stuff
}
}
I wanted to make sure the Solution from Nizam can be found in Kotlin to, since it is takeing bigger place every day:
val mDrawerLayout = this.findViewById(R.id.drawer_layout) as DrawerLayout
val mNavigationView = findViewById<View>(R.id.navigation) as NavigationView
Handle the navigation items in onCreate like this:
mNavigationView.setNavigationItemSelectedListener { it: MenuItem ->
when (it.itemId) {
R.id.nav_item1 -> doThis()
R.id.nav_item2-> doThat()
else -> {
true
}
}
}
Remember: Return Type has to be a boolean!
You have to use OnNavigationItemSelectedListener(MenuItem item) method.
for more check this documentation.
Here is a Java 8 approach with smaller boilerplate (no "implements" on Activity). Also helpful if your class is abstract and you don't want to implement this functionality in every other child:
#Override
protected void onCreate(
Bundle savedInstanceState) {
NavigationView navigationView =
findViewById(
R.id.navigationView);
navigationView.setNavigationItemSelectedListener(
MyActivity::onNavigationItemSelected);
}
public static boolean onNavigationItemSelected(MenuItem item) {
if (item.getId() == R.id.my_item) {
myItemClickHandler();
}
return false;
}
I have an app with a NavigationView and two tabs a and b. Two MenuItems in the NavigationView correspond to tab a and b so that, when tab a is selected, NavigationView MenuItem A should be selected, and the same for MenuItem B. Selecting MenuItem A and B should also change tab to a and b correspondingly. Selected here means changing the colors of the icon and text using a selector like this:
colors_navigationview.xml:
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_checked="true"
android:color="#color/red"
android:drawable="#color/red" />
<item android:state_checked="false"
android:color="#color/gray"
android:drawable="#color/gray" />
</selector>
NavigationView definition in layout:
<android.support.design.widget.NavigationView
android:id="#+id/my_navigationview"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/my_navigationview_header"
app:menu="#menu/my_navigationview"
app:itemIconTint="#drawable/colors_navigationview"
app:itemTextColor="#drawable/colors_navigationview"
/>
The MenuItems are contained in a SubMenu, defined like this:
my_navigationview.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/navigation_menu"
android:title="#string/foo">
<menu>
<item
android:id="#+id/my_navigationview_tab1"
android:icon="#drawable/fooicon"
android:title="#string/bar"/>
<item
android:id="#+id/my_navigationview_tab2"
android:icon="#drawable/baricon"
android:title="#string/barg"/>
</menu>
</item>
</menu>
The problem is that, when selecting tab a or b, be it by clicking the tabs directly or swiping the ViewPager for the tabs, the MenuItems A and Bs colors are not updated. Selecting the MenuItems directly in the NavigationView works, however, and the exact same code is called. Thus I am a bit baffled as to why this does not work.
To summarize:
Selecting a MenuItem in the NavigationView sets the correct color and changes tab. Everything is ok.
Selecting a tab changes the tab, but the selection color is not changed. I think the MenuItem is set to selected, since MenuItem.setSelected(true) is called.
What can I try to fix this issue? I am currently at a loss - this should be an easy thing to do IMO. I have tried the following and more:
Various suggestions from this question.
Invalidating various GUI elements, also the NavigationView and DrawerLayout.
Relevant methods in my Activity
#Override
public void onCreate()
{
// ...
// mTabLayout and mViewPager are created properly.
mTabLayout.setOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager)
{
#Override
public void onTabSelected(TabLayout.Tab tab)
{
super.onTabSelected(tab);
updateNavigationViewSelection();
}
});
}
#Override
public void onResume()
{
// ...
// To set correct NavigationView when resuming. Actually works ok at startup.
updateNavigationViewSelection();
}
public void updateNavigationViewSelection()
{
int currentItem = mViewPager.getCurrentItem();
selectNavigationMenuItem(currentItem);
}
public void selectNavigationMenuItem(int tab)
{
MenuItem menuItem = null;
NavigationView navigationView = (NavigationView) findViewById(R.id.my_navigationview);
switch (tab)
{
case TAB1:
menuItem = getNavigationMenuItemTab1();
break;
case TAB2:
menuItem = getNavigationMenuItemTab2();
break;
}
if (menuItem != null)
{
unselectAllNavigationMenuItems(); // Calls setChecked(false) on all MenuItems, may be commented out for testing.
// We arrive here, from onTabSelected(), onResume() and onNavigationItemSelected().
// onResume() sets the color correctly, as does onNavigationItemSelected(),
// but *not* when calling from onTabSelected(). All the values seem to be correct, but nothing happens.
// It seems that checked is set to true, but there is some invalidation missing.
// Invalidating NavigationView or DrawerLayout does nothing.
menuItem.setChecked(true);
}
}
#Override
public boolean onNavigationItemSelected(MenuItem menuItem)
{
switch (menuItem.getItemId())
{
case R.id.my_navigationview_tab1:
selectNavigationMenuItem(TAB1);
// Close drawer.
return true;
case R.id.my_navigationview_tab2:
selectNavigationMenuItem(TAB2);
// Close drawer.
return true;
default:
return false;
}
}
#Nullable
private MenuItem getNavigationMenuItemTab1()
{
MenuItem navigationMenu = getNavigationMenu();
return navigationMenu == null ? null : navigationMenu.getSubMenu().findItem(R.id.my_navigationview_tab1);
}
#Nullable
private MenuItem getNavigationMenuItemTab2()
{
MenuItem navigationMenu = getNavigationMenu();
return navigationMenu == null ? null : navigationMenu.getSubMenu().findItem(R.id.my_navigationview_tab2);
}
#Nullable
private MenuItem getNavigationMenu()
{
NavigationView navigationView = (NavigationView) findViewById(R.id.my_navigationview);
return navigationView == null ? null : navigationView.getMenu().findItem(R.id.navigation_menu);
}
private void unselectAllNavigationMenuItems()
{
MenuItem item;
item = getNavigationMenuItemTab1();
if (item != null)
item.setChecked(false);
item = getNavigationMenuItemTab2();
if (item != null)
item.setChecked(false);
}
Seems like i found a little workaround.
Several methods in like :
navigationView.getMenu().getItem(indx).setChecked(true);
navigationView.getMenu().findItem(someId).setChecked(true);
navigationView.setCheckedItem(someId);
navigationView.getMenu().performIdentifierAction(someId, 2);
did not work. But if you trigger the event by calling the navigation listener
onNavigationItemSelected(MenuItem)
method it works.
e.g. in your app:
onNavigationItemSelected(getNavigationMenuItemTab1());
This is the beahviour of my App (only 1 is right, of course):
Of course I want only one item at the moment checked.
I divided the items in two groups (to add the divider, see my previous question: How add horizontal separator in navdrawer? )
This is the nav_menu.xml:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single"
android:id="#+id/group1" >
<item
android:id="#+id/home"
android:checked="false"
android:icon="#drawable/ic_home_black_24dp"
android:title="#string/list_home" />
<item
android:id="#+id/list_event"
android:checked="false"
android:icon="#drawable/ic_list_black_24dp"
android:title="#string/list_event" />
</group>
<group
android:checkableBehavior="single"
android:id="#+id/group2" >
<item
android:id="#+id/settings"
android:checked="false"
android:icon="#drawable/ic_settings_black_24dp"
android:title="#string/settings" />
</group>
</menu>
This is the BaseApp that manage the NavDrawer:
package com.xx.views;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v7.app.ActionBarDrawerToggle;
import android.os.Bundle;
import android.view.View;
import com.xx.R;
import com.xx.mappers.DateManager;
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);
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame, new DashboardFragment());
fragmentTransaction.commit();
setNavDrawer();
// make home as checked
navigationView.getMenu().getItem(0).setChecked(true);
}
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
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()) {
case R.id.home:
DashboardFragment dashboardFragment = new DashboardFragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame, dashboardFragment,"DASHBOARD_FRAGMENT");
fragmentTransaction.commit();
return true;
case R.id.list_event:
ListEventFragment fragmentListEvent = new ListEventFragment();
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame, fragmentListEvent);
fragmentTransaction.commit();
return true;
case R.id.settings:
SettingsFragment fragmentSettings = new SettingsFragment();
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame, fragmentSettings);
fragmentTransaction.commit();
return true;
default:
return true;
}
}
});
// Initializing Drawer Layout and ActionBarToggle
drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
ActionBarDrawerToggle actionBarDrawerToggle =
new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.open_drawer, R.string.close_drawer){
#Override
public void onDrawerClosed(View drawerView) {
// Code here will be triggered once the drawer closes as we dont want anything
// to happen so we leave this blank
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
// Code here will be triggered once the drawer open as we dont want anything
// to happen so we leave this blank
super.onDrawerOpened(drawerView);
}
};
//Setting the actionbarToggle to drawer layout
drawerLayout.setDrawerListener(actionBarDrawerToggle);
//calling sync state is necessay or else your hamburger icon wont show up
actionBarDrawerToggle.syncState();
}
private void eraseTable(){
db=new DateManager(this);
db.resetTable();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Thank you very much
This could help you: Try to removing the tag android:checkableBehavior="single" from xml and set android:checkable = “true” for each item individually, then declare a MenuItem object in the activity and in onNavigationItemSelected event if previously declared MenuItem object is not null then set checked value as false for it and then save current selected menuItem received as parameter to earlier declared MenuItem object.
This will set checked selection on even subitems.
if (prevMenuItem != null) {
prevMenuItem.setChecked(false);
}
menuItem.setChecked(true);
mDrawerLayout.closeDrawers();
prevMenuItem = menuItem;
return true;
I found this solutions here
If you are using groups and android:checkableBehavior="single", then all you need to do is set the single item as the checked item in the navigation view (not simply the item as checked with item.setChecked(true)):
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
//item.setChecked(true); //Won't work, will leave previous item checked too.
navigationView.setCheckedItem(id); //this will check single item
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
Now, whether you select or emulate select for an item, it will check only one item at a time.
Put both group inside single group an set
android:checkableBehavior="single"
Create a parent group
You would have to implement a custom adapter, custom/model, custom function to uncheck other items on click.
I suggest you to use this library. Its a material navigation drawer implementation, it already has all this logic implemented. If you dont want to go with a lib, them you should check how its done on this library code and adapt to your needs.
I downloaded the sample app for the Navigation Drawer from
http://developer.android.com/training/implementing-navigation/nav-drawer.html
Now I'd like to add an icon to a specific item in the list; for example
Logout_icon + "Logout"
How can I do this? (Code please)
Assuming you are implementing the Navigation Drawer by a ListView, you will need to modify the layout for the list item by adding an ImageView. Then you should modify the adapter you use to populate the ListView so that it sets the src of the ImageView accordingly.
Quoting the guide you linked:
// Set the adapter for the list view
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mPlanetTitles));
That's where most of your changes will be wired: specifying a layout containing a TextView and and ImageView and creating a new Adapter.
As a convenience, you might create a class called something like NavDrawerItem which will have two fields: one for the icon, the other the caption which you'll display through a TextView.
In your adapter, be sure to consider the menu items for which you won't be displaying an icon.
try this
private ActionBarDrawerToggle mDrawerToggle;
mDrawerToggle=new ActionBarDrawerToggle(this,
mdrawerlayout,
R.drawable.ic_whats_hot,
R.string.app_name,
R.string.app_name)
{
public void onDrawerClosed(View view)
{
getActionBar().setTitle(mTitle);
invalidateOptionsMenu();
}
public void onDrawerOpened(View view)
{
getActionBar().setTitle(R.string.app_name);
invalidateOptionsMenu();
}
};
public boolean onOptionsItemSelected(MenuItem item)
{
if(mDrawerToggle.onOptionsItemSelected(item))
{
return true;
}
switch(item.getItemId())
{
case R.id.action_settings:
intent1=new Intent(MainActivity.this,ActivitySetting.class);
startActivity(intent1);
return true;
case R.id.action_websearch:
intent1=new Intent(Intent.ACTION_VIEW,Uri.parse("http://http://www.vogella.com/"));
startActivity(intent1);
return true;
default :
return super.onOptionsItemSelected(item);
}
}
try this in coding and in XML file
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/action_websearch"
android:showAsAction="always"
android:icon="#drawable/action_search"
android:title="search"/>
<item
android:id="#+id/action_settings"
android:title="Settings"
android:icon="#drawable/ic_launcher"
>
</item>
<item
android:id="#+id/action_logout"
android:title="logout"
android:icon="#drawable/ic_launcher"
/>