Set data to NavigationView menu items - android

If I add a custom item to my NavigationView menu, like so:
Menu menu = navigationView.getMenu();
MenuItem item = menu.add("Item 1");
How can I set data to the item (like an object) so that, when it's clicked/selected, I can pass that data to the activity it opens?

You can't set/add data to menu items. By looking at the documentation of add() method, it can be seen that you can set:
groupId - int: The group identifier that this item should be part of. This can be used to define groups of items for batch state changes. Normally use NONE if an item should not be in a group.
itemId - int: Unique item ID. Use NONE if you do not need a unique ID.
order - int: The order for the item. Use NONE if you do not care about the order. See getOrder().
title - CharSequence: The text to display for the item.
Therefore:
You need to set itemId and handle specific tasks inside onNavigationItemSelected()
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.id_of_menu_item_1) {
// handle intents and passing data
} else if (id == R.id.id_of_menu_item_2) {
// handle intents and passing data
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}

This doesn't make sense for me. MenuItem class only holds attributes relative to menu item. You cannot put other objects inside MenuItem instance. Take a look about MenuItem class:
MenuItem class
You can use repository pattern to get needed data on new activity or load object on current activity and pass to new activity using intent, just create a Bundle and put your serializable or parcelable object on it. You can make this when you handle onNavigationItemSelected(MenuItem item)

Related

How to change activity in Android Studio using a Navigation Drawer

mDrawerLayout = findViewById(R.id.drawer_layout)
val navigationView: NavigationView = findViewById(R.id.nav_view)
navigationView.setNavigationItemSelectedListener { menuItem ->
// set item as selected to persist highlight
menuItem.isChecked = true
// close drawer when item is tapped
mDrawerLayout.closeDrawers()
// Add code here to update the UI based on the item selected
// For example, swap UI fragments here
true
}
I have a navigation drawer in my app, and I can access it and click on the items listed there. However, what is the code I need to add above so that when an item is clicked, it opens up a new activity? I have 10 activities and don't know anything about fragments yet so have to set it so it opens a new activity for now.
#override
public boolean onNavigationItemSelected(MenuItem item)
{int id = item.getItemId();
// then use if and else to know which is selected}
'

Navigation drawer listview fragment

I want to make a navigation drawer which will populate by listview. Now i want that by clicking each item of the list, open a fragment as per my choice. How do I do this?
The NavigationDrawer doesn't use a ListView in the menu, NavigationDrawer uses directly Menu Items it means that in your source code you can add programmatically items to your menu as you need.
Your NavigationDrawer activity or whatever you named
you can add items to the menu using the
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// To Inflate the menu:
// this adds items to the navigation drawer menu if it is present.
getMenuInflater().inflate(R.menu.dashboard, menu);
return true;
}
by default this method create a static menu using a XML layout in the res/menu/menu_file.xml
but if you follow the next source code you will be able to add more items to your navigation drawer programmatically
the Method add() overloads:
add (int titleRes)
add (CharSequence title)
add (int groupId, int itemId, int order, int titleRes);
add (int groupId, int itemId, int order, CharSequence title);
if you already have all the names of your new menu items in an array like itemsName
you can use something like this:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
for(String itemName : itemsName){
int itemId = Arrays.asList(itemsName).indexOf(itemName);
menu.add(Menu.NONE, itemId, Menu.NONE, itemName);
}
return true;
}
and to manage the click event, on every one, you need to solve it depending on your array of actions to take, in your dynamic array, because you need to know deterministic every action that your menu item need to do or behave, as a menu option.
But in general your click listener for those menu items you use something like this:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
//here you need the logic of what action
//your item is going to take
//but that is up to you
//how do you want to know what to do
//with a dynamic unknown array of options.
if (itemId == 0){
doSomething();
return true;
}
return false;
}
}
enjoy!!!

How to change Navigation Item Selected programmatically

When I created a new project I used Navigation Drawer Activity
app screen
Now each menu item when I click on it will open a fragment by calling a method name replacement.
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_home) {
replaceFragment(0);
setTit = "Your State Info.";
setTitle(setTit);
} else if (id == R.id.nav_flashcards) {
replaceFragment(1);
setTit = "Flash Cards";
setTitle(setTit);
in fragment 1 I have a RadioGroup when the checked change will open the fragmet depends on the radio checked.
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
RadioButton radioButton = (RadioButton)getActivity().findViewById(i);
if(radioButton.getTag()==1)
((MainActivity) getActivity()).replaceFragment(0);
else if ((radioButton.getTag()==2))
((MainActivity) getActivity()).replaceFragment(2);
}
The App work fine , but the issue is how can I change the Navigation Item Selected and also change the title for the action bar.
it's possible to use this way
((MainActivity) getActivity()).onNavigationItemSelected(menuitem);
but from the fragment how can I access the the items in the menu>activity_main_drawer.xml and pass it through menuitem
This works for me..
NavigationView navigationView = (NavigationView) getActivity().findViewById(R.id.nav_view);
navigationView.getMenu().getItem(2).setChecked(true);
In your fragment you have to add setOptionsMenu(true)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// TODO Add your menu entries here
super.onCreateOptionsMenu(menu, inflater);
}
question is not clear.
whole point of navigation drawer with fragments is to access navigation and its main toolbar all over the fragments with a single main activity.(the blue color one in your image, you should be able to change this anytime when you load a fragment)
But you need to make the frame/parent view of the fragments blow the tool bar view(that's why normally it comes with two XMLs, activtyMain.xml and contentMain.xml where content main is included below the tool bar in activityMain.XML) so you create fragments view match_parent to this contentMain.xml ,you can see toolbar is accessible to the each and every fragment you add in that view because its in the main activity where fragment/s add.
so you have a main activity and inside that you have fragment/s frame. Doesn't matter what fragment you load you can still have the access to main toolbar.
so once you check which item got clicked in navigationDrawer you load the fragment related to that right?. and there access the main toolbar of the mainActivity and do the changes that you need to display.That's it!
if (id == R.id.nav_whatever) {
// access toolBar or any view in main activity and do the changes
// call relevant fragment
}
But you cannot access that toolbar or mainActivity views inside your Fragment class that you try to attempt.
Edit :
Keep a Boolean in a Constant class or something similar,
then when you click on your button on second fragment change the value .
Now let's say Boolean is true
Then you click the navigation drawer again
// keep the id as it is and use the Boolean to check where you needs to go
if (id == R.id.nav_whatever) {
if(boolianName){
// boolianName is true go load second fragment
}else{
// load firstfragment
}
}
If you use Navegation drawer, you can use this code, put it on onCreate method:
NavigationView navigationView = (NavigationView) getActivity().findViewById(R.id.nav_view);
navigationView.getMenu().getItem(2).setChecked(true);

Android: get item position of menu

I have a navigation drawer, with some voices.
navigationView = (NavigationView) findViewById(R.id.navigation_view);
One of that voices has id "list_member", in position #2 (so it has id 1).
I need to get that position, to use in another part of code.
Something of this pseudocode:
if (navigationView.getMenu().item has label == "list_member") {
id_position = this.getId();
}
navigationView.getMenu().getItem(id_position).setChecked(state);
You could add a tag with setTag() to your View then iterate over the container of your navigation views and return the child position.
you can use setNavigationItemSelectedListener as like below :
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.list_member:
// Do your code here...
return true;
default:
return trToast.makeText(getApplicationContext(),"Somethings Wrong",Toast.LENGTH_SHORT).show();ue;
}
}
});
Every View has a so called tag property, I believe that would suite your need to store such info which would act as "label" in your context.
Details here: http://developer.android.com/reference/android/view/View.html#attr_android:tag
You can set this property either in the layout resource XML or programmatically by calling view.setTag(Object tag) or setTag(int key, Object tag) and then retreive it by calling view.getTag() or view.getTag(int key).
Or you can also call view.findViewWithTag(Object tag) on parent view to find a view with a specific tag in it's child views
(http://developer.android.com/reference/android/view/View.html#findViewWithTag(java.lang.Object))
in you case it would like something like this:
((Checkable) navigationView.getMenu().findViewWithTag("list_member")).setChecked(state);
hope this helps

How to get all menu items id Android

I can get all the items from the actionbar with getItem() but I need to compare their id's with a particular id. How can I do this?
You can get actionBar menu items id by calling pMenu.getItem();
You can use changing methods of these menu items by overriding the method:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action buttons
switch(item.getItemId()) {
case R.id.action_stats:
break;
}
}

Categories

Resources