Navigation drawer: How do I set the selected item at startup? - android

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);

Related

How to change the Background color of selected item in the Navigation Drawer

I was working on Nav drawer on my app.
I have made the background of my nav drawer #000000(Black). Whenever I select any item the textcolor of text changes from #E44F50(Carrot Red) to black but I cant change the background color of the selected item.
All I want is to change the background color of selected Item from black to carrot red.
Here is the github link to my app-
https://github.com/manmeet-22/NewsSnips-app.git
<android.support.design.widget.NavigationView
android:id="#+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#color/colorPrimary"
app:headerLayout="#layout/header"
app:itemIconTint="#drawable/drawer_item" //changing text color
app:itemTextAppearance="#style/TextAppearance20"
app:itemTextColor="#color/drawer_item"
app:itemBackground="#drawable/drawer_selected_item" //trying to change backgroundcolor the same way
app:menu="#menu/drawer"
tools:context="com.androidexample.newssnips.app.NavigationDrawerFragment"/>
</android.support.v4.widget.DrawerLayout>
In this I tried changing the background color like I did for the text but my app crashes.
here is my drawer_selected_item.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="#color/colorAccent" android:state_selected="true"/>
<item android:color="#android:color/transparent"/>
</selector>
here is my drawer_item.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="#color/colorPrimary" android:state_checked="true" />
<item android:color="#color/colorAccent" />
</selector>
Here is my MainActivity.java:
navigationView = (NavigationView) findViewById(R.id.navigation_view);
navigationView.setItemIconTintList(null);
Menu menu = navigationView.getMenu();
//For chnaging the textColor and textSize of group's Name ie. Category
MenuItem categoryName= menu.findItem(R.id.categoryGroup);
SpannableString s = new SpannableString(categoryName.getTitle());
s.setSpan(new TextAppearanceSpan(this, R.style.TextAppearance25), 0, s.length(), 0);
//For changing the Text of action bar as the selected category
categoryName.setTitle(s);
//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 open the Appopriate news accordingly
switch (menuItem.getItemId()) {
case R.id.itemWorld:
GAURDIAN_REQUEST_URL = "http://content.guardianapis.com/search?api-key=f51fa87d-8a55-4fc1-b552-8fa6eb98dee4&section=world";
setTitle("World News");
basicDefaults();
return true;
case R.id.itemFootball:
GAURDIAN_REQUEST_URL = "http://content.guardianapis.com/search?api-key=f51fa87d-8a55-4fc1-b552-8fa6eb98dee4&section=football";
setTitle("Football News");
basicDefaults();
return true;
case R.id.itemFashion:
GAURDIAN_REQUEST_URL = "http://content.guardianapis.com/search?api-key=f51fa87d-8a55-4fc1-b552-8fa6eb98dee4&section=fashion";
setTitle("Fashion News");
basicDefaults();
return true;
case R.id.itemSports:
GAURDIAN_REQUEST_URL = "http://content.guardianapis.com/search?api-key=f51fa87d-8a55-4fc1-b552-8fa6eb98dee4&section=sport";
setTitle("Sports News");
basicDefaults();
return true;
case R.id.itemBusiness:
GAURDIAN_REQUEST_URL = "http://content.guardianapis.com/search?api-key=f51fa87d-8a55-4fc1-b552-8fa6eb98dee4&section=business";
setTitle("Business News");
basicDefaults();
return true;
case R.id.itemTechnology:
GAURDIAN_REQUEST_URL = "http://content.guardianapis.com/search?api-key=f51fa87d-8a55-4fc1-b552-8fa6eb98dee4&section=technology";
setTitle("Technology News");
basicDefaults();
return true;
case R.id.itemOpinion:
GAURDIAN_REQUEST_URL = "http://content.guardianapis.com/search?api-key=f51fa87d-8a55-4fc1-b552-8fa6eb98dee4&section=commentisfree";
setTitle("Opinions");
basicDefaults();
return true;
case R.id.itemCulture:
GAURDIAN_REQUEST_URL = "http://content.guardianapis.com/search?api-key=f51fa87d-8a55-4fc1-b552-8fa6eb98dee4&section=culture";
setTitle("Culture News");
basicDefaults();
return true;
case R.id.itemTravel:
GAURDIAN_REQUEST_URL = "http://content.guardianapis.com/search?api-key=f51fa87d-8a55-4fc1-b552-8fa6eb98dee4&section=travel";
setTitle("Travel News");
basicDefaults();
return true;
case R.id.itemLifestyle:
GAURDIAN_REQUEST_URL = "http://content.guardianapis.com/search?api-key=f51fa87d-8a55-4fc1-b552-8fa6eb98dee4&section=lifeandstyle";
setTitle("LifeStyle News");
basicDefaults();
return true;
case R.id.itemEnvironment:
GAURDIAN_REQUEST_URL = "http://content.guardianapis.com/search?api-key=f51fa87d-8a55-4fc1-b552-8fa6eb98dee4&section=environment";
setTitle("Environment News");
basicDefaults();
return true;
default:
Toast.makeText(getApplicationContext(), "Somethings Wrong", Toast.LENGTH_SHORT).show();
return true;
}
}
});
// Initializing Drawer Layout and ActionBarToggle
drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.openDrawer, R.string.closeDrawer) {
#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);
}
};
//calling sync state is necessay or else your hamburger icon wont show up
actionBarDrawerToggle.syncState();
}
PS.- I have tried implementing other methods too like
adding this in apptheme in styles.xml file.
<item name="android:activatedBackgroundIndicator">#drawable/drawer_selected_item</item>
But still I cant find my solution.
Please help it is the last thing that is left in my project.
I have got the solution-
In the NavigationView I did-
app:itemBackground="#drawable/drawer_selected_item"
Thus my NavigationView looks like-
<android.support.design.widget.NavigationView
android:id="#+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#color/colorPrimary"
app:headerLayout="#layout/header"
app:itemIconTint="#drawable/drawer_item"
app:itemTextAppearance="#style/TextAppearance20"
app:itemTextColor="#drawable/drawer_item"
app:menu="#menu/drawer"
app:itemBackground="#drawable/drawer_selected_item"
tools:context="com.androidexample.newssnips.app.NavigationDrawerFragment" />
In the drawer_selected_item I modified file as-
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:drawable="#color/colorAccent"/>
<item android:drawable="#android:color/transparent" />
</selector>
NavigationView has a method called setItemTextColor(). It uses a ColorStateList.navigationView.setItemTextColor(). with ColorStateList as a parameter.
Adding explanation to Caspian's answer:
Android Developers Documentation provides ColorStateList so you can play around on different states of a View in android.
Example Code here: ColorStateList Android Example

onNavigationItemSelected not working in NavigationView

Please can someone help me with fragments from the navigation drawer, for some reason I can't get them to work and all the code looks right.
Here is the link to the source code.
Use this code:
navigationView = (NavigationView) findViewById(R.id.navigationView);
navigationView.bringToFront();
Have a look at your MainActivity.java.
You have implemented the callbacks for NavigationView.OnNavigationItemSelectedListener in MainActivity as below,
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
// blah blah
}
Also check the setupDrawerContent method.
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
drawerLayout.closeDrawers();
return true;
}
});
}
In this method you are creating a local OnNavigationItemSelectedListener.
So you are not using the OnNavigationItemSelectedListener that you have overridden in MainActivity.
The solution is to use this as argument for setNavigationItemSelectedListener. By doing this all your clicks will go the onNavigationItemSelected of MainActivity rather than going to the local onNavigationItemSelected.
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(this);
}
Also move the code in the local onNavigationItemSelected to the onNavigationItemSelected of MainActivity.
So your onNavigationItemSelected will be something like this,
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
// Handle navigation view item clicks here.
int id = menuItem.getItemId();
menuItem.setChecked(true);
drawerLayout.closeDrawers();
if (id == R.id.nav_home) {
// Handle the home action
Toast.makeText(this, "Home", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_the_wetlands) {
Toast.makeText(this, "The Wetlands", Toast.LENGTH_SHORT).show();
TheWetlandsFragment theWetlandsFragment = new TheWetlandsFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.relativelayout_for_fragment, theWetlandsFragment, theWetlandsFragment.getTag()).commit();
} else if (id == R.id.nav_the_mistbelt_forests) {
Toast.makeText(this, "The Mistbelt Forests", Toast.LENGTH_SHORT).show();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
Also change your activity_main_drawer_view.xml as follows to solve the multiple selection issue you have in the Navigation Drawer,
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_home"
android:icon="#drawable/ic_dashboard"
android:title="Home" />
</group>
<item android:title="Information">
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_the_wetlands"
android:icon="#drawable/ic_event"
android:title="The Wetlands" />
<item
android:id="#+id/nav_the_mistbelt_forests"
android:icon="#drawable/ic_event"
android:title="The Mistbelt Forests" />
<item
android:id="#+id/nav_the_grasslands"
android:icon="#drawable/ic_event"
android:title="The Grasslands" />
</group>
</item>
<item android:title="Quick Go To">
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_accommodation"
android:icon="#drawable/ic_event"
android:title="Accommodation" />
<item
android:id="#+id/nav_cuisine"
android:icon="#drawable/ic_forum"
android:title="Cuisine" />
<item
android:id="#+id/nav_leisure_activites"
android:icon="#drawable/ic_forum"
android:title="Leisure & Activites" />
<item
android:id="#+id/nav_agri_tourism"
android:icon="#drawable/ic_forum"
android:title="Agri-tourism" />
<item
android:id="#+id/nav_education"
android:icon="#drawable/ic_forum"
android:title="Education" />
<item
android:id="#+id/nav_arts_crafts_decor"
android:icon="#drawable/ic_forum"
android:title="Arts, Crafts & DeCor" />
<item
android:id="#+id/nav_selective_shopping"
android:icon="#drawable/ic_forum"
android:title="Selective Shopping" />
<item
android:id="#+id/nav_for_children"
android:icon="#drawable/ic_forum"
android:title="For Children" />
</group>
</item>
<item android:title="Midlands Animals">
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_midlands_birding_checklist"
android:icon="#drawable/ic_dashboard"
android:title="Midlands Birding Checklist" />
<item
android:id="#+id/nav_midlands_mammals_checklist"
android:icon="#drawable/ic_dashboard"
android:title="Midlands Mammals Checklist" />
</group>
</item>
</menu>
Good luck.
Don't use
NavigationUI.setupWithNavController(navigationView, navController);
instead of it do this
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Toast.makeText(MainActivity.this, "clicked", Toast.LENGTH_SHORT).show();
return false;
}
});
I have also faced the same problem some time back, and at the end i realized that i have not wrote the 2nd line of the following code
navigationView = (NavigationView) findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(this);
you make sure you have written the same otherwise your listener will not work
in my case i forgot to initialize navigation menu.
kindly follow following code:
public void initSideMenu() {
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);
}
happy coding...
Make sure you have implement the interface NavigationView.OnNavigationItemSelectedListener.
Second point make sure to add these lines otherwise listnere will not be called.
navigationView=(NavigationView) findviewbyid(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(this);
Add this line
navigationView.bringToFront();
Its works for me

Android - DrawerLayout and Toolbar not visible on first opening

I'm currently developing an android app using a Toolbar and a DrawerLayout. The main content is a custom SurfaceView where I can draw differents shapes, text ... The left menu is a NavigationView and is used as a toolbox (I select what I want to draw from the left and I draw it on the SurfaceView). Everything is working fine except for one thing : when I first try to open the left menu (by clicking the toolbar or by sliding from the left side of the screen) the items are not visible. And while I don't click on any item (which are not visible) they stay invisible. The problem is only fixed when I click on an invisible item, after that the menu is working fine. I'm using a custom theme to hide the status bar and remove the default actionbar :
<style name="AppBaseTheme" parent="#style/Theme.AppCompat.Light.NoActionBar"></style>
<style name="ColladiaTheme" parent="AppBaseTheme">
<!-- Remove action bar -->
<item name="android:windowActionBar">false</item>
<item name="android:windowNoTitle">true</item>
<!-- Remove status bar -->
<item name="android:windowFullscreen">true</item>
<item name="android:windowContentOverlay">#null</item>
<!-- Material theme -->
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
</style>
Here are some screenshots :
Menu open but not visible
Menu visible after clicking an item
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout 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"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.ia04nf28.colladia.DrawColladiaView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/draw_view" />
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_height="?attr/actionBarSize"
android:layout_width="?attr/actionBarSize"
android:minHeight="?attr/actionBarSize"
android:background="?attr/colorPrimary">
</android.support.v7.widget.Toolbar>
</FrameLayout>
<!-- Left navigation menu -->
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="?attr/actionBarSize"
android:layout_height="match_parent"
android:layout_marginTop="?attr/actionBarSize"
android:layout_gravity="start"
android:fitsSystemWindows="false"
app:menu="#menu/nav_view_items" >
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
And here is the Activity code :
public class DrawActivity extends AppCompatActivity {
private static final String TAG = "DrawActivity";
private DrawerLayout drawer;
ActionBarDrawerToggle drawerToggle;
private NavigationView nav;
private DrawColladiaView colladiaView;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_draw);
// Change toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
colladiaView = (DrawColladiaView) findViewById(R.id.draw_view);
colladiaView.setApplicationCtx(getApplicationContext());
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
// Add burger button
drawerToggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(drawerToggle);
// Removes overlay
drawer.setScrimColor(Color.TRANSPARENT);
drawer.closeDrawers();
nav = (NavigationView) findViewById(R.id.nav_view);
setUpDrawerContent(nav);
}
public void setUpDrawerContent(NavigationView nav)
{
nav.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem item) {
selectDrawerItem(item);
return true;
}
}
);
}
public void selectDrawerItem(MenuItem item)
{
switch(item.getItemId())
{
case R.id.nav_home:
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(intent);
break;
default:
Element newElement = ElementFactory.createElement(getApplicationContext(), item.getTitle().toString());
if (newElement != null) colladiaView.insertNewElement(newElement);
drawer.closeDrawers();
break;
}
}
#Override
public void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onBackPressed() {
Log.d(TAG, "onBackPressed");
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
}
It looks like you should be overriding onOptionsItemSelected instead of onBackPressed:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// This will toggle the drawer if android.R.id.home is clicked
if(drawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle any other menu item selections...
return super.onOptionsItemSelected;
}
To be honest, I do not see where your drawer is ever being opened. It should still respond to a swipe from the left edge though. This code will set it to be toggled when android.R.id.home is clicked (the back/menu button).

NavigationView slow to open / Skipping frames (Android Design Lib)

I'm using a NavigationView supplied by the Android Design Library. I've found after adding a few items to it that is performing quite poorly. On first launch it takes a second or so to open for the firs time. Here's a screenshot of the UI.
I'll try to post some of the relevant bits of code.
Drawer XML
<group android:checkableBehavior="single">
<item
android:id="#+id/home"
android:checked="false"
android:icon="#drawable/ic_home"
android:title="Home" />
<item
android:id="#+id/about"
android:checked="false"
android:icon="#drawable/ic_about"
android:title="About" />
<item
android:id="#+id/gallery"
android:checked="false"
android:icon="#drawable/ic_gallery"
android:title="Gallery" />
<item
android:id="#+id/settings"
android:icon="#drawable/ic_action_settings"
android:title="Settings" />
<item
android:id="#+id/navigation_subheader"
android:title="Categories">
<menu>
<item
android:id="#+id/science"
android:checked="false"
android:icon="#drawable/ic_science"
android:title="Science" />
<item
android:id="#+id/parenting"
android:checked="false"
android:icon="#drawable/ic_parenting"
android:title="Parenting" />
<item
android:id="#+id/android"
android:checked="false"
android:icon="#drawable/ic_android"
android:title="Android" />
<item
android:id="#+id/technology"
android:checked="false"
android:icon="#drawable/ic_tech"
android:title="Technology" />
<item
android:title=""
android:checkable="false"
android:visible="false"
android:orderInCategory="200"/>
</menu>
</item>
</group>
MainAct
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initializing Toolbar and setting it as the actionbar
toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
setSupportActionBar(toolbar);
//Initializing NavigationView
navigationView = (NavigationView) findViewById(R.id.navigation_view);
//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();
Log.v(TAG + "-S", "Pre_Switch = " + mCurCheckPosition);
//Check to see which item was being clicked and perform appropriate action
switch (menuItem.getItemId()) {
case R.id.home:
homeFragment();
return true;
case R.id.about:
webFragment();
return true;
case R.id.gallery:
galleryFragment();
return true;
case R.id.science:
scienceFragment();
return true;
case R.id.parenting:
parentingFragment();
return true;
case R.id.android:
androidFragment();
return true;
case R.id.technology:
technologyFragment();
return true;
case R.id.settings:
Intent i = new Intent(MainActivity.this, SettingsActivity.class);
startActivity(i);
default:
return true;
}
}
});
// Initializing Drawer Layout and ActionBarToggle
drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.openDrawer, R.string.closeDrawer){
#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();
}
And finally here is the error im seeing in the logs from the Choreographer, i'm hoping this is just a bug in the lib however im wondering if someone else came across this and might have a work around.
I/Choreographer﹕ Skipped 117 frames! The application may be doing too much work on its main thread.
Full source is available here: https://github.com/caman9119/The_Jones_Theory
Found the issue in my header.xml I was using a background.png that was 1080x720p. I scaled the image down to ~400x300 and voila, interesting problem indeed.
If you are using dynamic images for the background (using user facebook or g+ banner by example) and using Picasso this piece of code can be usefull:
ImageView background = (ImageView) findViewById(R.id.background);
Picasso
.with(context)
.load([Your image source here])
.fit()
.centerCrop()
.into(background)
Had the same problem, i was using 512 x 512 images in the drawer list. All images were initially placed in the 'drawable' folder but when i moved them to the 'drawable-xxhdpi' folder, it was butter smooth.

ActionBarActivity doesn´t shows my AppIcon

I´m trying to add in my ActionBar my app icon, but I was reading on Google Developers and I can get the solution. I´m doing this on my ActivityMain:
actionBar = getSupportActionBar();
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setIcon(R.drawable.ic_launcher);
But it doesn´t work.
This is my first day with Android and I just want make an ActionBar with the main icon on the left and an icon search.
Thank You.
With API21 you should use the new Toolbar class.
Put the Toolbar in your layout:
<android.support.v7.widget.Toolbar
android:id=”#+id/my_awesome_toolbar"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:minHeight="attr/actionBarSize"
android:background="?attr/colorPrimary" />
Then in your code (onCreate in your Activity for example):
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setNavigationIcon(R.drawable.ic_myNavigationIcon);
You can find more info in the official post.
Add:
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setLogo(R.drawable.ic_launcher)
You should be changing the logo, which is by default the same as the launcher icon.
You should do the following steps to implement ActionBar :
1 - Extend ActionBarActivity like this :
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Notice to import this :
import android.support.v7.app.ActionBarActivity;
2 - Add lines below into onCreate :
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setIcon(R.drawable.ic_launcher);
3- Create your xml menu under res/menu/your_menu.xml
somthing like this :
your_menu.xml
<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">
<item
android:id="#+id/action_settings"
android:orderInCategory="100"
android:title="#string/action_settings"
app:showAsAction="ifRoom"/>
</menu>
4- Inflate the menu to the action bar, and handle the action bar item clicks :
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.your_menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
Hope this help you!!!

Categories

Resources