Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should "android: onOptionsItemSelected" return true or false

Tags:

android

In onOptionsItemSelected... I saw some code that are different in the switch block.

Case 1 (Normally seen)

public boolean onOptionsItemSelected (MenueItem item)        switch (item.getItemId()){              case R.id.item1:              startActivity (new Intent (this, PrefsActivity.class));              break;        }        return true 

Case 2 (unsure of why it's set up this way)

public boolean onOptionsItemSelected(MenuItem item) {        switch (item.getItemId()) {                case MENU_NEW_GAME:                newGame();                return true;        }        return false; 

My Question

What are the differences between Case 1 and Case 2?

like image 409
kleaver Avatar asked Apr 19 '11 16:04

kleaver


People also ask

What does onOptionsItemSelected do?

onOptionsItemSelected() method used to handling the event of option menu i.e. which menu action is triggered and what should be the outcome of that action etc.

What is onCreateOptionsMenu in Android?

Find the onCreateOptionsMenu(Menu menu) method which needs to override in Activity class. This creates menu and returns Boolean value. inflate inflates a menu hierarchy from XML resource. public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater(). inflate(R.


1 Answers

Per the documentation for onOptionsItemSelected()

Returns

boolean Return false to allow normal menu processing to proceed, true to consume it here.

The if returned true the click event will be consumed by the onOptionsItemSelect() call and won't fall through to other item click functions. If your return false it may check the ID of the event in other item selection functions.

Your method will still work, but may result in unnecessary calls to other functions. The ID will ultimately fall through those functions since there is no switch to catch it, but return false is more correct.

like image 86
Will Tate Avatar answered Oct 07 '22 17:10

Will Tate