5

As I'm new to Android programming, I've encountered another little thing that I don't understand. Why does the onCreateOptionsMenu method below return super.onCreateOptionsMenu instead of just calling super.onCreateOptionsMenu (as it's done in the onCreate method)?

(This is from an Android tutorial.)

public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu items for use in the action bar
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main_activity_actions, menu);
    return super.onCreateOptionsMenu(menu);
}

(I've found no duplicate question on StackOverflow. I'm probably asking a silly question or I'm just bad at searching.)

PenguinCake
  • 317
  • 2
  • 4
  • 9
  • 3
    hmmm to call onCreateOptionsMenu of the super class but it will be better to return `did_i_create_menu_in_derived_class || super.onCreateOptionsMenu(menu)` which will be in this example always `true` ... from doc `Returns: You must return true for the menu to be displayed; if you return false it will not be shown.` – Selvin Aug 05 '14 at 15:15
  • It allows the superclass implementation to execute and. This is useful if you extend a Fragment or Activity that has some base menu items already that you want included in your subclass implementation. – Karakuri Aug 05 '14 at 15:19
  • because it has to return something. since it's a boolean method and all. – njzk2 Aug 05 '14 at 15:27

3 Answers3

4

onCreate()'s return type is void, while onCreateOptionsMenu() returns boolean, that's why the return.

Eduard B.
  • 6,735
  • 4
  • 27
  • 38
2

The super.onCreateOptionsMenu(menu): will execute any code that has to be executed for the options menu to work properly. The code you write adds extra functionality/ decides properties of the options menu.

ChristianCuevas
  • 2,672
  • 3
  • 19
  • 24
  • So that's kind of the same as the super.onCreate(savedInstanceState) does in the onCreate method, right? But why is it returned here instead of just called? – PenguinCake Aug 05 '14 at 15:28
  • @PenguinCake Because this method has a return type of boolean, so you call super (which also has a return type of boolean) and it does everything it needs to do, and also returns true so that the calling code can proceed smoothly. If super returns false, then something must be very wrong, and this is a way of making that obvious. – ChristianCuevas Aug 05 '14 at 15:32
0

You must return true for the menu to be displayed, if you return false it will not be shown.

tarn
  • 546
  • 6
  • 10