user569890
user569890

Reputation: 21

different behavior with method onCreateOptionsMenu

I found something confused for me in this article http://developer.android.com/guide/topics/ui/menus.html

Below is simple piece of code and output When I start application on android 3.0

  1. and 2. line system executed as soon as the activity is created

The 3. and 4. lines were printed when menu was pressed and menu item was chosen

Probem is line 5 and buttonHandler method, that method calls invalidateOptionsMenu(); and result of that calls is line 6 and 7

Why system calls onCreateOptionsMenu before onPrepareOptionsMenu even they have written

On Android 3.0 and higher, you must call invalidateOptionsMenu() when you want to update the menu, because the menu is always open. The system will then call onPrepareOptionsMenu() so you can update the menu items.

In this case onCreateOptionsMenu is called every time after invalidateOptionsMenu(), but when I start application on android 2.3 onCreateOptionsMenu was called only once.

1 INFO/System.out(382): onCreateOptionsMenu
2 INFO/System.out(382): onPrepareOptionsMenu
3 INFO/System.out(382): onPrepareOptionsMenu
4 INFO/System.out(382): onOptionsItemSelected
5 INFO/System.out(382): buttonHandler
6 INFO/System.out(382): onCreateOptionsMenu
7 INFO/System.out(382): onPrepareOptionsMenu

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
}

public boolean onCreateOptionsMenu(Menu menu) {
    System.out.println("onCreateOptionsMenu");
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.game_menu, menu);
    return true;
}

public boolean onPrepareOptionsMenu(Menu menu) {
    System.out.println("onPrepareOptionsMenu");
    return super.onPrepareOptionsMenu(menu);
}

public boolean onOptionsItemSelected(MenuItem item) {
    System.out.println("onOptionsItemSelected");
    return super.onOptionsItemSelected(item);
}

public void buttonHandler(View v){
    System.out.println("buttonHandler");
    invalidateOptionsMenu();
}

Upvotes: 2

Views: 3410

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006539

That is probably a documentation bug. I would expect onCreateOptionsMenu() to be called after invalidateOptionsMenu().

Upvotes: 3

Related Questions