I showed previously how to create an Options menu and how to add Menu item to it.
Now I am going to show how to handle options menu item selection.
I will show code snippet and after whole example.
For this handling need to override onOptionsItemSelected(MenuItem item) method in your Activity:
@Overridepublic boolean onOptionsItemSelected(MenuItem item){switch (item.getItemId()){case OK_MENU_ITEM:showMsg("Ok");break}return super.onOptionsItemSelected(item)}And whole example:
import android.app.Activity;import android.os.Bundle;import android.view.Gravity;import android.view.Menu;import android.view.MenuItem;import android.widget.Toast;public class Main extends Activity{private static final int OK_MENU_ITEM = Menu.FIRST;private static final int SAVE_MENU_ITEM = OK_MENU_ITEM + 1;private static final int BACK_MENU_ITEM = SAVE_MENU_ITEM + 1;@Overridepublic void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main)}@Overridepublic boolean onCreateOptionsMenu(Menu menu){menu.add(0,OK_MENU_ITEM,0,"Ok");menu.add(0,SAVE_MENU_ITEM,0,"Save");menu.add(0,BACK_MENU_ITEM,0,"Back");return super.onCreateOptionsMenu(menu)}@Overridepublic boolean onOptionsItemSelected(MenuItem item){switch (item.getItemId()){case OK_MENU_ITEM:showMsg("Ok");break;case SAVE_MENU_ITEM:showMsg("Save");break;case BACK_MENU_ITEM:showMsg("Back");break}return super.onOptionsItemSelected(item)}private void showMsg(String msg){Toast toast = Toast.makeText(Main.this,msg,Toast.LENGTH_LONG);toast.setGravity(Gravity.CENTER,toast.getXOffset() / 2,toast.getYOffset() / 2);toast.show()}}As you can see it is very easy to handle menu item selections.
No related posts.

Recent Comments