Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Android Finishing Up

Aritro Banerjee
PLUS
Aritro Banerjee
Courses Plus Student 2,567 Points

in 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
seal-mask
.a{fill-rule:evenodd;}techdegree
J A
Full Stack JavaScript Techdegree Student 4,616 Points

The 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.

Just 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

Jason Wiram
Jason Wiram
42,184 Points

It 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.