Should "android: onOptionsItemSelected" return true or false
When I used Android Studio to generate a generic app, the template code for onOptionsItemSelected() returns true if item consumed otherwise it passes the call onto the super class.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_mymenuaction) {
return true;
}
return super.onOptionsItemSelected(item);
}
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.
As per documentation
true --> Event Consumed here, now It should not be forwarded for other event
false --> Forward for other event to get consumed
This boolean return type actually benefits when we are working with multiple fragments and every fragment has their own Options menu and override OnOptionItemSelected(Mainly in tablet design).
In this case android trace every fragment's OnOptionItemSelected() method, to avoid that
a) If any fragment is consuming event in onOptionsItemSelected() return "true"(to stop) else return "false"
b) If We return false then It will trace other connected fragment's onOptionsItemSelected()
method until it ends all fragment or somebody consumes It.
Here I have tried to explain from diagram
Green color boundary is fragment-1 and Red color boundary is fragment-2
both fragment has their own Optionmenu which I have highlighted
Now If we click any of OptionmenuItem It will check Implementation of onOptionsItemSelected() in both fragments
If any fragment is consuming event onOptionsItemSelected return true, By this it would never try for other fragment and we can reduce overhead of Android operation system.