Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialAritro Banerjee
Courses Plus Student 2,567 Pointsin item.setChecked, how does Android Studio know which menu item I am referring to here?
in item.setChecked, how does Android Studio know which menu item I am referring to here?
For example in this code block
case R.id.red: red=!red;
updateColors();
item.setChecked(red);
break;
How does the compiler know which item I am talking about( since there are five menu items in this video nextImage,red,green,blue,reset).
NOTE: The red passed as a parameter in
items.setChecked(red);
refers to a boolean variable red and not the item red.
2 Answers
J A
Full Stack JavaScript Techdegree Student 4,646 PointsThe function onOptionsItemSelected
takes a MenuItem
object as its only parameter. This object is the menu item that was just clicked/tapped. This function is called when any menu item is clicked and it receives that exact item that was just clicked.
This is why we have a switch case in the function; we get the object that was just tapped (whatever item in the menu it may be) and we need to identify it using its ID and act on it appropriately.
Jason Wiram
42,762 PointsIt would appear in your scenario that you are getting the item with the id of "red."
case R.id.red:
That would be the item you are setting as checked. It is hard to confirm what you are trying to do and what might be wrong because you apparently have two different things named "red." (one an item id and one a boolean variable). That is very confusing and a bad practice. Names should be unique and descriptive. It will help you and others understand your code.
Alfonso Castro
7,147 PointsAlfonso Castro
7,147 PointsJust to be more explicit in JA answer: By the switch you are selecting the CASE when the RED ITEM is clicked. -Remember you are OVERRIDING an existent Android function. -You don't see the code that calls onOptionsItemSelected, but it pass the item clicked like he says