How to hide navigation drawer item while the respective fragment is opened - android

In my app, I used navigation drawer. Here I listed all the items.
From the image,the items are,
Home
Filter & Sort
WishList
Shop
MyOrder
Settings
LogOut
If I am in the Fragment of Shop , I need to hide it. How to do this?
Please help me.

You can handle it in fragments onAttach method. Set the visibility of perticular item according to your need.
#Override
public void onAttach(Context context) {
super.onAttach(context);
YourActivity activity = (YourActivity)context;
NavigationView navigationView = (NavigationView) activity.findViewById(R.id.yournavigationviewid);
navigationView.getMenu().findItem(R.id.youritemid).setVisible(false);
}

inside your setNavigationItemSelectedListener where you get the selected menuItem, you can implement the code. Also you require to store the instance of the hidden menu item to make it visible later
MenuItem prevMenuItem;
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
if(prevMenuItem != null) prevMenuItem.setVisible(true) //making visible the previously hidden item.
menuItem.setVisible(false);
prevMenuItem = menuItem //storing the instance of currently hidden item to make it visible later.
return true;
}
});

In your public onNavigationItemSelected(MenuItem item) if you are setting one fragment then automatically drawer will hide. I'm doing like this :
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
toolbar.setTitle(item.toString());
int id = item.getItemId();
if (id == R.id.dashboard) {
fragment = new DashboardFragment();
} else if (id == R.id.manage_users) {
}else{
}
setFragmentLayout(fragment);
return true;
}
Set your fragment according to your requirements.

You can hide the drawer using mDrawerLayout.closeDrawers() in onNavigationItemSelected Listener like this:
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
switch (menuItem.getItemId()) {
case R.id.navigation_item_shop:
//do your stuffs or attach fragment
mDrawerLayout.closeDrawers();
return true;
default:
return true;
}
}
}

on the fragments overide the onAttach method. Set the visibility of for items your don't need.
#Override
public void onAttach(Context context) {
super.onAttach(context);
MainActivity activity = (MainActivity)context;
NavigationView navigationView = (NavigationView) activity.findViewById(R.id.navmenu);
// hide the menu items not related to this fragment
Menu m = navigationView.getMenu();
m.findItem(R.id.first).setVisible(false);
m.findItem(R.id.second).setVisible(false);
m.findItem(R.id.therd).setVisible(false);
//and so on
}

Related

Scroll navigation drawer to bottom at item click

Hello i am new to android. I want the navigation drawer scroll to bottom on an item click. Is it possible?
if (id == R.id.setting){
--CODE--
}
Here if setting is selected i want the navigation drawer to scroll down to bottom. How can it do it? please help.
If I understood it correctly, id.settings is a button, to add the functionality when a user clicks a button you should use this code:
Button settingsBtn = (Button) findViewById(R.id.settings);
settingsBtn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
--CODE--
}
});
You can use onNavigationItemSelected() to handle NavigationDrawer items.
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.setting: {
// do something when clicked
break;
}
}
//close navigation drawer
mDrawerLayout.closeDrawer(GravityCompat.START);
return true;
}
And add implements NavigationView.OnNavigationItemSelectedListener to your Activity :
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener
Remember to initialize and set the listener in onCreate():
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);

Fragment to fragment communication within a NavigationDrawer

In my app, I have a NavigationDrawer in my app that has two fragments I want to display (Fragment1 and Fragment2) in a MainActivity. I have a menu item in my ToolBar in Fragment 1 when clicked I want to my MainActivity to switch to Fragment2 and have the NavigationView reflect the UI changes.
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawer;
private Toolbar toolbar;
private NavigationView nvDrawer;
private ActionBarDrawerToggle drawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.flContent, new BookListFragment()).commit();
}
// Set a Toolbar to replace the ActionBar.
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Find our drawer view
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerToggle = setupDrawerToggle();
// Tie DrawerLayout events to the ActionBarToggle
mDrawer.addDrawerListener(drawerToggle);
// Find our drawer view
nvDrawer = (NavigationView) findViewById(R.id.nvView);
// Setup drawer view
setupDrawerContent(nvDrawer);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
drawerToggle.onConfigurationChanged(newConfig);
}
private ActionBarDrawerToggle setupDrawerToggle() {
// NOTE: Make sure you pass in a valid toolbar reference. ActionBarDrawToggle() does not require it
// and will not render the hamburger icon without it.
return new ActionBarDrawerToggle(this, mDrawer, toolbar, R.string.drawer_open, R.string.drawer_close);
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
selectDrawerItem(menuItem);
return true;
}
});
}
public void selectDrawerItem(MenuItem menuItem) {
// Create a new fragment and specify the fragment to show based on nav item clicked
Fragment fragment = null;
Class fragmentClass;
switch (menuItem.getItemId()) {
case R.id.book_list_fragment:
fragmentClass = BookListFragment.class;
break;
case R.id.discover_fragment:
fragmentClass = DiscoverFragment.class;
break;
default:
fragmentClass = BookListFragment.class;
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
// Highlight the selected item has been done by NavigationView
menuItem.setChecked(true);
// Set action bar title
setTitle(menuItem.getTitle());
// Close the navigation drawer
mDrawer.closeDrawers();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
switch (item.getItemId()) {
case android.R.id.home:
mDrawer.openDrawer(GravityCompat.START);
return true;
}
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Fragment Code
public class BookListFragment extends Fragment {
...
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_insert_dummy_data:
insertBook();
return true;
case R.id.action_delete_all_entries:
int rowsDeleted = getContext().getContentResolver().delete(ShelfHelpContract.BookEntry.CONTENT_URI, null, null);
return true;
case R.id.action_discover:
/*TODO Here I want to open another Fragment and have it reflect
in the UI on my NavigationView and MainActivity
*/
return true;
}
return super.onOptionsItemSelected(item);
....
}
The following code takes care of replacing your Fragment when the user clicks on one of the navigation items
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
Besides replacing the fragment you will want to also update the title of your activity using something along the lines of:
((AppCompatActivity)getActivity()).getSupportActionBar().setTitle("Home");
And finally you must tell your NavigationView to highlight the right item using the setChecked(boolean) function. It should look something like this:
nvDrawer.getMenu().findItem(/*your item id*/).setChecked(true);
If you want to perform the same action when the user clicks on a menu item then make sure to add a new case to the switch block found in your onOptionsItemSelected(MenuItem item) and just call the same lines passing in the right Fragment

close navigation drawer after clicking on any of its item

I have used navigation drawer in my app. When user click any of its item it will go to another activity but when user comes back to the drawer page it is still open. How to close that drawer once its item is clicked.
You can use drawerLayout.closeDrawers(); to close the NavigationDrawer before you go to another Activity
Use closeDrawer() method to close the drawer and start your other activity on the listener of drawer.
For Example.
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
//Start your activity
}
DrawerLayout mDrawerLayout= (DrawerLayout) findViewById(R.id.drawer_layout)
closeDrawer(); // called when you want to close
public void closeDrawer()
{
if (mDrawerLayout.isDrawerOpen(GravityCompat.START))
{
mDrawerLayout.closeDrawer(GravityCompat.START);
}
}
I think you missed closeDrawer() just call this method before launching other on click of Navigation Item Intent
drawerLayout.closeDrawer(GravityCompat.END);
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
// Create a new fragment and specify the fragment to show based on nav item clicked
Fragment fragment = null;
Class fragmentClass = null;
if (id == R.id.nav_item1) {
fragmentClass = home.class;
// Handle the camera action
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
if(fragmentClass.newInstance() instanceof Fragment) {
fragment = (Fragment) fragmentClass.newInstance();
if (fragmentClass.getSimpleName().equals("home")) {
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.home_layout, fragment).commit();
// Highlight the selected item has been done by NavigationView
item.setChecked(true);
// Set action bar title
setTitle(item.getTitle());
// Close the navigation drawer
drawer.closeDrawers();
}
}
Just add closeDrawer() inside onNavigationItemSelected() to close the drawer on selecting any item on Navigation Drawer.
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
//write your if logic here
drawer.closeDrawer(GravityCompat.START,true);
return false;
}
Probably the navigation view is not in the front. Try getting it to front by mNavigationView.bringToFront();.

Get selected menu item's index value in the navigation drawer

I have implemented navigation drawer, it is working fine. The only problem that I have to make selected item to deselect when the navigationdrawer closes. I wonder how could I able to get the index value of selected menu item.
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(false);
}
)}
One way to do is store menu item ID in variable e.g checkedItemID
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItemID=menuItem.getItemId();
}
)}
Then on implement
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_close) {
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
// Do whatever you want here
navigationView.getMenu().findItem(menuItemID).setChecked(false);
}
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
// Do whatever you want here
}
};
// Set the drawer toggle as the DrawerListener
mDrawerLayout.setDrawerListener(mDrawerToggle);
Make a variable position of int datatype. Firstly set its value to 0 and onNavigationItemSelected change its value to menuItem index(like 0 or 1 or 2 and so on).Now this position will provide you the index of selected menuItem.
int position = 0;
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.first:
position = 0;
break;
case R.id.second:
position = 1;
break;
case R.id.third:
position = 2;
break;
}
return true;
}
});
Try this to get navigation item at position 0 getItem(index) will give you desired item
navigationView.getMenu().getItem(selectedposition).setChecked(false);
also use this link for reference for getting seleted item http://thegeekyland.blogspot.in/2015/11/navigation-drawer-how-set-selected-item.html
use below code for getting selected position
int selectedposition= 0;
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.firstitemid:
selectedposition= 0;
break;
case R.id.seconditemid:
selectedposition= 1;
break;
case R.id.thirditemid:
selectedposition= 2;
break;
}
return true;
}
});
Another easy way that worked for me
public boolean onNavigationItemSelected(MenuItem item) {
int index = (item.getItemId() % item.getGroupId())-1;
....
}
I think, this would be much more efficient than using For loop or Switch case.
If you still have problems then my suggestion would be to check your Item Id and group Id in Log-cat so that you would have a better understanding of what you are dealing with.
This is all you need, it deselects and selects the new one
navigationView.setCheckedItem(item.getItemId());
And it should go at the bottom of onNavigationItemSelected.
To make it more clear here's an example
#Override
public boolean onNavigationItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_home:
controller.setFragment(new HomeFragment());
break;
case R.id.nav_settings:
controller.setFragment(new SettingsFragment());
break;
case R.id.nav_logout:
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
intent.putExtra(autoLogin, false);
startActivity(intent);
break;
}
navigationView.setCheckedItem(item.getItemId());
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return false;
}
First assign your navigationMenu to a class field
private NavigationView navigationView;
private int currentPosition;
...
navigationView = (NavigationView) findViewById(R.id.nav_view);
Now in the menu callback you can loop over the menu items :
public boolean onNavigationItemSelected(MenuItem item) {
for (int i=0;i<navigationView.getMenu().size();i++){
if(item==navigationView.getMenu().getItem(i)){
currentPosition=i;
break;
}
}
....
}
You can change the order of the menu items without breaking anything

How to select the first item in a navigation drawer and open a fragment on application start

I have created MainActivity with NavigationView. When Activity is opened I want to automatically select the first item in the navigation drawer and open Fragment under that item. I've searched a lot but didn't find any proper solutions.
What is the proper way to do this ?
Main Activity:
public class MainActivity extends AppCompatActivity implements Config {
private NavigationView navigationView;
private DrawerLayout drawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitleTextColor(getResources().getColor(R.color.colorIcons));
if (null != getSupportActionBar())
getSupportActionBar().setLogo(R.drawable.ic_blogger_white);
//Start PostListFragmentWebView
/*PostListFragmentWebView postListFragmentWebView = new PostListFragmentWebView();
getSupportFragmentManager().beginTransaction()
.replace(R.id.frame, postListFragmentWebView)
.commit();*/
//Initializing NavigationView
navigationView = (NavigationView) findViewById(R.id.navigationView);
//Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
//Checking if the item is in checked state or not, if not set it to 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 clicked and perform the appropriate action.
switch (menuItem.getItemId()) {
case R.id.posts:
PostListFragmentWebView postListFragment = new PostListFragmentWebView();
getSupportFragmentManager().beginTransaction()
.replace(R.id.frame, postListFragment)
.commit();
return true;
case R.id.pages:
PageListFragmentWebView pagetListFragment = new PageListFragmentWebView();
getSupportFragmentManager().beginTransaction()
.replace(R.id.frame, pagetListFragment)
.commit();
return true;
case R.id.blog:
BlogInfoFragmentWebView blogInfoFragment = new BlogInfoFragmentWebView();
getSupportFragmentManager().beginTransaction()
.replace(R.id.frame, blogInfoFragment)
.commit();
return true;
default:
Toast.makeText(getApplicationContext(), getResources().getString(R.string.drawer_error), Toast.LENGTH_SHORT).show();
return true;
}
}
});
// Initializing Drawer Layout and ActionBarToggle
drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
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 don't 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);
drawerLayout.getChildAt(0).setSelected(true);
//calling sync state is necessary or else your hamburger icon wont show up
actionBarDrawerToggle.syncState();
}
}
In onCreate(), following code will load the first item's fragment upon first start:
if (savedInstanceState == null) {
navigationView.getMenu().performIdentifierAction(R.id.posts, 0);
}
Thanks to calvinfly for this comment.
Add android:checked="true" to your first menu item.
And manually select one item, using
getSupportFragmentManager().beginTransaction().replace(R.id.frame, postListFragment).commit();
to open fragment.
Instead of normal listener ...
navView.setNavigationItemSelected(new Navigation.View.OnNavigationItemSelectedListener() {bla, bla, bla})
Create the listener as an Obj:
NavigationView.OnNavigationItemSelectedListener navViewListener;
navView.setNavigationItemSelectedListener(navViewListener = new NavigationView.OnNavigationItemSelectedListener() {bla, bla, bla})
...and use the Obj to trigger the listener event:
navViewListener.onNavigationItemSelected(navView.getMenu().getItem(0));
...where getItem(0) is the first menu item.
Use a method getItem(0).setChecked(true) or android:checked="true" at its menu item XML definition.
You could also use navigationView.setCheckedItem(R.id.default)(javadoc) after you setup your navigationview.
just add this code in onCreate method:
FragmentTransaction ftrans = getFragmentManager().beginTransaction();
ftrans.replace(R.id.container, <yourfragment>).commit();
Work for me !
This can be done even better while considering orientation and other configuration changes. We could select whatever nav drawer menuitem depending on whether we are coming from a previous state. Check: For the Navigation drawer wielding Activity:-
public static final String SELECTED_NAV_MENU_KEY = "selected_nav_menu_key";
// The selected grid position
private int mSelectedNavMenuIndex = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_demo);
...........................................................
navigationView.setNavigationItemSelectedListener(this);
if (savedInstanceState != null) {
// Recover assets
mSelectedNavMenuIndex = savedInstanceState.getInt(SELECTED_NAV_MENU_KEY);
// Recover menu as selected
MenuItem menuItem = navigationView.getMenu().getItem(mSelectedNavMenuIndex);
toggleNavMenuItemCheck(menuItem);
navigationView.getMenu().performIdentifierAction(menuItem.getItemId(), mSelectedNavMenuIndex);
return;
} else {
MenuItem menuItem = navigationView.getMenu().getItem(mSelectedNavMenuIndex);
toggleNavMenuItemCheck(menuItem);
navigationView.getMenu().performIdentifierAction(menuItem.getItemId(), mSelectedNavMenuIndex);
}
}
The toggle method that helps uncheck or check the menu item
private void toggleNavMenuItemCheck(MenuItem menuItem) {
if (menuItem.isChecked()){
menuItem.setChecked(false);
} else {
menuItem.setChecked(true);
}
}
This is how I save the state of the selected menu item. Check:-
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.nav_explore:
showExploreFragment(null);
mSelectedNavMenuIndex = 0;
break;
case R.id.nav_orders:
mSelectedNavMenuIndex = 1;
break;
case R.id.nav_settings:
mSelectedNavMenuIndex = 2;
break;
default:
showExploreFragment(null);
mSelectedNavMenuIndex = 0;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
// Save any important data for recovery
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(SELECTED_NAV_MENU_KEY, mSelectedNavMenuIndex);
}
NB: The line with code:
navigationView.getMenu().performIdentifierAction(menuItem.getItemId(), mSelectedNavMenuIndex);
Can be replaced by the code:
onNavigationItemSelected(menuItem);
in menu.xml remember to mention android:checkable="true" for single item and android:checkableBehavior="single" for a group of items.
<item
android:id="#+id/pos_item_help"
android:checkable="true"
android:title="Help" />
<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>
then inside NavigationItemSelectedListener use setCheckedItem(R.id.item_id_in_menu) to make it selected.
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.pos_item_pos:
navigationView.setCheckedItem(R.id.pos_item_pos);
break;
case R.id.pos_item_orders:
navigationView.setCheckedItem(R.id.pos_item_orders);
break;
default:
}
return true;
}
And you do not have to do the dirty task of managing the selected item anymore. navigationView manages it by self.
1.) To land to the HomeFragment initially, use this inside your onCreate() in MainActivity:
Fragment fragment = new HomeFragment();
// replacing the fragment
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
}
2.) To set the item as selected in navigationDrawer set the item as checked in navigation_menu.xml
android:checked = "true"

Categories

Resources