Search This Blog

Thursday, March 8, 2012

Creating the Options Menu and Itemselected methods in android

You can use the following code inside the menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/menu1"
android:alphabeticShortcut="s"
android:title="menu1 title"
/>
<item
android:id="@+id/menu2"
android:alphabeticShortcut="t"
android:title="menu2 title"
/>
</menu>

now the two methods for the invoking the menu and function which is to be called on the item selected.

@override
public boolean onCreateOptionsMenu (Menu menu){
super.onCreateOptionsMenu(menu);
//menu.add(R.menu.main_menu);
//menu.add(Menu.NONE, 101,Menu.FIRST,this.getResources().getString(R.string.Title));
MenuInflater mi = getMenuInflater();
mi.inflate(R.menu.main_menu, menu);
return true;
}




you can use the both the method of invoking the menu. First one by the menu.add and second one by the inflating the menu.xml file Now on the itemselectedlistner is used by the following code.

public boolean onOptionsItemSelected(MenuItem item){
              switch(item.getItemId()){
                       case R.id.menu1:
                       // your code here
                       case R.id.menu2:
                       // your code here
               }
     return false;
}



just pass the id in switch-case and do whatever you want by selecting the those menu.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.