Tuesday, November 10, 2009

Creating Menu & SubMenu in Android

In this tutorial, I am going to explain, how to create options menu, subMenu etc..

From Activity class, just override the method, onCreateOptionsMenu(). Then inside the method, create the menu, according to our wish.

Then, override another method called, onOptionsItemSelected. In this, if we select any, menu, what we have to do, will code in this. That means, menu events will be handled in this method.


public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch(item.getItemId()) {
case 0: Toast.makeText(this, "clicked Menu 1",
Toast.LENGTH_SHORT).show();
break;
case 1: Toast.makeText(this, "clicked Menu 2",
Toast.LENGTH_SHORT).show();
break;
case 2: Toast.makeText(this, "clicked Menu 3",
Toast.LENGTH_SHORT).show();
break;
}
return true;
}



The screenshot will be look like this.



For adding submenu, we have to use the function called addSubMenu(), in the Menu class

the code is,


public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
SubMenu sub = menu.addSubMenu(0,1,0, "SubMenu");
sub.add(0,11,0,"SubMenu 1");
sub.add(0,12,0,"SubMenu 2");
sub.add(0,13,0,"SubMenu 3");
return true;
}



The screen shot of this is like this..



When click in the sub menu, we will see the screen like this..


No comments:

Post a Comment

Androidians