Introduction
Menus are an integral part of any app. It is very rare to see an app without option menus. Likewise, we will try an Options menu in this article with a small demo.
For this, we will use the inflate() method of the MenuInflater class.
Procedure
Step 1
Before we start we will add a few packages that we will use in this project.
- import android.view.Menu;
- import android.view.MenuItem;
- import android.widget.Toast;
Step 2
Similar to an Activity's XML file, we will code the MENU file that itself is a XML file. And here we add the value of the items.
In the new Android SDK Package, Eclipse generates a dummy Menu that you will get in the res/menu.
By default, you have a main.xml file that contains the menu-items.
We will now add some items to the XML file.
Code
- <item
- android:id="@+id/one"
- android:title="One" />
-
- <item
- android:id="@+id/two"
- android:title="Second"/>
-
- <item
- android:id="@+id/third"
- android:title="Third"/>
Step 3
We have now done the design part, we will now code our Java file. So, get to the MainActivity.java file and ensure that you have this default code:
Code
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
-
- // Inflate the menu; this adds items to the action bar if it is present.
- getMenuInflater().inflate(R.menu.main, menu);
- return true;
- }
It will create your Option menu. And you can see the infalte() method that populates the main.xml file to the Options Menu.
Step 4
We will now add the click listener property. Since it's not a button, that's why we have various ways to do this. In the Options Menu or any Menu, there is an onOptionItemSelected() method.
Code
- public boolean onOptionsItemSelected(MenuItem item) {
-
- switch(item.getItemId()){
- case R.id.one:
- Toast.makeText(MainActivity.this, "First is Selected", Toast.LENGTH_LONG).show();
- return false;
-
-
- case R.id.two:
- Toast.makeText(MainActivity.this, "Second is Selected", Toast.LENGTH_LONG).show();;
- return false;
-
-
- case R.id.third:
- Toast.makeText(MainActivity.this, "Third is seleced", Toast.LENGTH_LONG).show();;
- return false;
-
- }
- return false;
-
- }
Here we are using the switch() way that is a convenient way to judge which option is selected.
item.getItemId() will return the ID of the selected item and depending on that, it will popup the toast message.
If you have done your code right, then it will look like:
If you encounter any problem then please refer to Quick fix (Ctrl+1), as it is capable of solving most of the problems or just go to the enclosed project file.