Dynamic Menu



This app starts with a menu of one item, and adds an additional item each time you make a selection. The menu is modified by Java methods. See Changing menu items at runtime.

In Android < 3.0, SDK < 11, onPrepareOptionsMenu is called each time we press the Android Menu button. It makes an incremental change to the menu. In Android ≥ 3.0, SDK ≥ 11, onCreateOptionsMenu and onPrepareOptionsMenu are both called when we call invalidateOptinsMenu. To make the app run correctly for both versions, onPrepareOptionsMenu has to clear out the menu.

Source code in Dynamic.zip

  1. DynamicActivity.java: onCreateOptionsMenu, onPrepareOptionsMenu, onOptionsItemSelected.
  2. main.xml: a LinearLayout containing a TextView.
  3. AndroidManifest.xml: the activity element has android:screenOrientation="landscape".