Search This Blog

28 May 2010

Menus

Let's start with creating a basic app:
F:\work> mvn archetype:generate -DarchetypeCatalog=http://kallisti.eoti.org:8081/content/repositories/snapshots/archetype-catalog.xml
Choose the galatea-archetype plugin
groupId: org.eoti.android
artifactId: MenuTest
version: 1.0-SNAPSHOT
package: org.eoti.android


Assuming your emulator is running...
F:\work> cd MenuTest
F:\work\MenuTest> mvn clean install

Create a new folder src\main\android\res\menu

Create a new file src\main\android\res\menu\mainmenu.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <group android:id="@+id/first_menu">
        <item android:id="@+id/second"
              android:title="Open Second Menu" />
        <item android:id="@+id/about_first"
              android:title="About First Menu" />
    </group>
    <group android:id="@+id/second_menu">
        <item android:id="@+id/first"
              android:title="Open First Menu" />
        <item android:id="@+id/about_second"
              android:title="About Second Menu" />
    </group>
    <item android:id="@+id/quit"
          android:title="Quit" />
</menu>

Let's write your activity (src\main\java\org\eoti\android\MenuTestActivity.java in my case):

public class MenuTestActivity extends Activity {
    private static String TAG = "MenuTest";
    private Menu menu;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.mainmenu, menu);
        this.menu = menu;
        menu.setGroupVisible(R.id.first_menu, true);
        menu.setGroupVisible(R.id.second_menu, false);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId())
        {
            case R.id.first:
                menu.setGroupVisible(R.id.first_menu, true);
                menu.setGroupVisible(R.id.second_menu, false);
                return true;
            case R.id.second:
                menu.setGroupVisible(R.id.first_menu, false);
                menu.setGroupVisible(R.id.second_menu, true);
                return true;
        }
        return false;
    }
}
   
Redeploy (mvn clean install) and run the app.
When you hit the menu, you will see 3 options: Open Second Menu, About First Menu, and Quit.
Only the first one does anything.  If you select Open Second Menu, then the menu will change (though hidden).
Click menu again and you will now see: Open First Menu, About Second Menu, and Quit.
Again, only Open First Menu does anything.

No comments:

Post a Comment