First we will create Simple Option menus as Follows Steps
Download Android Option Menu with Xml file: Project
- Create a new Android Project Name MenuDemo
- Add XML file into res/menus/menu.xml for that follow the following Steps
- Right Click on Project Folder
- Select New
- Select "Android XML file"
- Give name of file As "menus"
- Select "menu" type of Resource.
- Say Finish.
Add the Following code.....
- Override
the onCreateOptionMenu() Method in the Activity class files where you want to
add menu. From
- Right click in Activity file
- \Select ”Source”
- Select “Override / Implement Methods “
- Select “onCreateOptionMenu()” method
- Say Ok.
- We will Use MenuInflater class to show the menus by put following code in onCreateOptionMenu()
@Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater mi = getMenuInflater(); mi.inflate(R.menu.menus, menu); return super.onCreateOptionsMenu(menu); }
- We will Interact with the menu Item as follows using onOptionsItemSelected() method.
@Override public boolean onOptionsItemSelected(MenuItem item) { // TODO Auto-generated method stub switch (item.getItemId()) { case R.id.item1: Toast.makeText(getApplicationContext(), "Hello!", 5).show(); break; case R.id.item2: Intent i = new Intent(getApplicationContext(), ActivityA.class); startActivity(i); break; case R.id.item3: Intent dial = new Intent(Intent.ACTION_DIAL); startActivity(dial); break; default: break; } return super.onOptionsItemSelected(item); }
Where We have done following actions Menu wise....
Item1 : We wiill Display Toast "Hello"
Item2 : We call the New Activity "Activity A"
Item3 : We display the Default Dialer of Android. - Run the Android Apps
- First Click on Menu Button of Device as follows..
- That will display the following screen as follows
- Press On the "Hello" that will show you Following Screen..
- Then Again Press Menu Button Click on "New Activity" Item
- Then Press Back Button. Then Again Click on "Dial" Item. that shows following Dialer.
No comments:
Post a Comment