Skip to main content

Create Android Options Menu Programatically

In this post we are going to learn about how to show an android menu without using a separate menu layout xml file. You can create a menu in two ways.
1. Create the menu by inflate an xml file located in the menu folder using the MenuInflater object.
2. Add the menu items dynamically (by writing code) to menu using the add() method.

Here I demonstrate how to add the menu items dynamically to an options menu.

Step 1:  Override the onCreateOptionsMenu in the MainActivity.java file.
  @Override  
   public boolean onCreateOptionsMenu(Menu menu) {  
        // TODO Auto-generated method stub  
   }  
Ads by Google


Step 2: Add each menu items to the menu using the add() method and the Menu object.
            add(arg1, arg2, arg3, arg4);
            The add method takes three arguments.
            arg1  =  Indicates the group id. You can pass Menu.NONE if there is no group available.
            arg2  =   Indicates the item id. 
            arg 3 = Indicates the order number in witch the item appear in the menu. You can pass                                      Menu.NONE if you not consider the item order.
            arg 4 = Indicates the title of the menu item.
 MenuItem it1 = menu.add(Menu.NONE, send_email, Menu.NONE, "Send Email");  
 MenuItem it2 = menu.add(Menu.NONE, make_call, Menu.NONE, "Make Call");  
 MenuItem it3 = menu.add(Menu.NONE, send_cloud, Menu.NONE, "Send Cloud");  

Step 3: Add an icon for the menu using setIcon( )  method.
 it1.setIcon(R.drawable.ic_action_email);  
 it2.setIcon(R.drawable.ic_action_call);  
 it3.setIcon(R.drawable.ic_action_cloud);  

Step 4: You can make the menu items visible on the Action bar using the setShowAsAction() method.
 it1.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);  
 it2.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);  
 it3.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);  

Handling the click events

For handling the click events of the options menu, you need to override the onOptionsItemSelected() method. You can get the selected item id using the MenuItem object.
  @Override  
   public boolean onOptionsItemSelected(MenuItem item) {  
        // TODO Auto-generated method stub  
        switch (item.getItemId()) {  
           case send_email:  
                  Toast.makeText(getBaseContext(), "You select the email option ", Toast.LENGTH_SHORT).show();  
                return true;  
           case make_call:  
             Toast.makeText(getBaseContext(), "You select the call option ", Toast.LENGTH_SHORT).show();  
           return true;       
           case send_cloud:  
             Toast.makeText(getBaseContext(), "You select the cloud option ", Toast.LENGTH_SHORT).show();  
           return true;  
           default:  
                return false;  
   }  

Here is the full source code
 package com.menutest;  
 import android.app.Activity;  
 import android.os.Bundle;  
 import android.view.Menu;  
 import android.view.MenuItem;  
 import android.widget.Toast;  
 public class MainActivity extends Activity {  
      private static final int send_email = 0;  
      private static final int make_call = 1;  
      private static final int send_cloud = 2;  
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.activity_main);  
   }  
   @Override  
   public boolean onCreateOptionsMenu(Menu menu) {  
        // TODO Auto-generated method stub  
        MenuItem it1 = menu.add(Menu.NONE, send_email, Menu.NONE, "Send Email");  
        MenuItem it2 = menu.add(Menu.NONE, make_call, Menu.NONE, "Make Call");  
        MenuItem it3 = menu.add(Menu.NONE, send_cloud, Menu.NONE, "Send Cloud");  
        it1.setIcon(R.drawable.ic_action_email);  
        it2.setIcon(R.drawable.ic_action_call);  
        it3.setIcon(R.drawable.ic_action_cloud);  
        it1.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);  
        it2.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);  
        it3.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);  
        return super.onCreateOptionsMenu(menu);  
   }  
   @Override  
   public boolean onOptionsItemSelected(MenuItem item) {  
        // TODO Auto-generated method stub  
        switch (item.getItemId()) {  
           case send_email:  
                  Toast.makeText(getBaseContext(), "You select the email option ", Toast.LENGTH_SHORT).show();  
                return true;  
           case make_call:  
             Toast.makeText(getBaseContext(), "You select the call option ", Toast.LENGTH_SHORT).show();  
           return true;       
           case send_cloud:  
             Toast.makeText(getBaseContext(), "You select the cloud option ", Toast.LENGTH_SHORT).show();  
           return true;  
           default:  
                return false;  
   }  
   }   
 }  

create dynamic menu in android


                                  Click Here to view the video tutorial of this topic.



Comments

Popular posts from this blog

Android MySQL Database Operations

In this post we are going to learn about how to connect to MySQL Database from your Android Application and perform database operations. Here we create an android app that contain some login Activity through which the user can retrieve information from database and a registration Activity through which the user can add information into the database.  First you need to have the following components installed in your development machine.  1. Database : Here we use the MySQL database. 2. Web Server : Here we use the Apache Web Server. 3. Server side Scripting Language :   Here we use PHP for server side scripting. 4. Android Development environment : You must install android sdk and android studio.   I recommend you to download and install WAMPSERVER. The wamp server installer contains the following components. Apache Server Application MySQL Database PHP/phpMyAdmin First we have to create the database and table in MySQL. You can use the...

Schedule Android Background Job Using Firebase JobDispatcher

From Android version 8.0 (Oreo) on wards there are limitations in executing background services and there are some limitations in receiving certain broadcasts. The android team implement all these restrictions to improve app performance and device battery life. If your app target API 26 then you have to consider some other mechanisms to do your background job.  Fortunately there is JobScheduler API that solve the problem regarding the background job limitations in newer versions of android. Google suggests Android App developers to use the JobScheduler API for their background job execution rather than using a background service.  But the problem is that the android framework JobScheduler API is available from android API version 21(Lollipop) and above. If your app support start from Lollipop and above then you can go for the framework JobScheduler API for your background job. If your App support start from android API lower than 21 then you can use the Firebase ...

"please correct the errors on this form" adsense error simple solution

Many of the bloggers now facing the problem with their adsense widgets. Whenever try to add the new  adsense link unit using the blogger widgets, it shows the error " please correct the errors on this form " as shown bellow. In blogger you can add the adsense units in two ways. First one is adding the adsense using the blogger widgets(Most of the beginners doing this) and the second method is to obtain the adsense code from the adsense login page and place it into the targeted position on the blog. To improve the revenue from adsense you have to place the appropriate ad unit into the right position. The adsense link units are very important for increasing the adsense revenue. So due to this error many of the bloggers are unable to place the link units.  Here is the solution for the problem. 1. Login into your adsense and blogger account. 2. Now make sure that only two adsense widgets (units) are present on your blog, this is because Google allows onl...