Andy Andy - 3 months ago 7
Android Question

What is the correct way to create a menu in Android?

I am going through a tutorial, and it showed this example code to make a menu:

public void onCreateOptionsMenu(Menu m) {
super.onCreateOptionsMenu(m);
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.time_list_menu, m);
}


I got an error and so I changed it to boolean, which is what it is now, and so I did this instead, and its working:

public boolean onCreateOptionsMenu(Menu m) {
super.onCreateOptionsMenu(m);
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.time_list_menu, m);
return true;
}


But I also have stuff like this from another question here on stack overflow

Understanding why onCreateOptionsMenu is not displaying a menu

The Android doc also has this:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.game_menu, menu);
return true;
}


Where did the call to super go and why is it not necessary? What is the correct way to make a menu if I am doing it wrong?

While I am on the subject, the Doc also shows @Override, but I don't have it, and its working. I am just confused as to whether that is necessary if the methods are explicitly being overridden. I appreciate the help. IF any clarification is needed, please let me know.

Answer

To address your two specific problems:

  1. super.onCreateMenuOptions: In general it is a good idea to call base class functions in this way when you intend to refine their actions. In this case it makes no difference (as far as you can tell) but the documentation recommends it so you should execute it to ensure future android version compatibility.
  2. @Override: this annotation is voluntary but is very useful, it ensure that the method signature matches that of the underlying base class. This means that if you declare the method slightly wrong (in the sense of different to the method that it is overriding) the compiler will pick up the discrepancy (as opposed to just considering it a new method and not calling it in the context)

Thus both are useful and correct if not strictly needed.

Comments