Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android option menu with icon

Tags:

android

How to show icon with option menu.I have tried the following code but my option menu is without image icon.I am using android version 4.0 for developing app.

Java code :

 public boolean onCreateOptionsMenu(Menu menu) {
            super.onCreateOptionsMenu(menu);
             menu.add("Add Contacts").setIcon(
                    R.drawable.ic_launcher);

            return true;
        }

Following is my app's screen shot

enter image description here

I need image to be displayed on the top of "Add Contacts" item.

like image 739
sonia Avatar asked Feb 21 '13 05:02

sonia


People also ask

How do I show icons in option menu?

Click res → New → Vector Asset . Choose the icon that you want by clicking on the android icon, click “Next” button and then click “Finish”. 6- Now we can add android menu items with icons, we will have 4 menu items. 1 menu item will be the root while the other 3 menu items will be grouped under a single Menu .

What is option menu android?

The options menu is the primary collection of menu items for an activity. It's where you should place actions that have a global impact on the app, such as "Search," "Compose email," and "Settings." See the section about Creating an Options Menu.

Where is the option menu?

1- Android Option Menu In Android, an Option Menu is a set of primary options of an application which users can select one of the options to perform an action. The Option Menu appears on the right side of the App Bar.


3 Answers

Override OnPrepareOptionsMenu and add icon from there too

and if its for above 3.0, use android:showAsAction in xml.

eg. android:showAsAction="ifRoom|withText"

like image 172
xmen Avatar answered Sep 25 '22 05:09

xmen


I tried the code in two line and it works:

public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        menu.add("Add Contacts");
        menu.getItem(0).setIcon(R.drawable.ic_launcher);
        return true;
}
like image 26
Panthesilea Avatar answered Sep 23 '22 05:09

Panthesilea


You can create a custom menu like this:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/add_contacts"
          android:icon="@drawable/ic_launcher"
          android:title="@string/add_contacts"
         />
</menu>

And then inflate it

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.my_menu, menu);
    return true;
}

More on this here: http://developer.android.com/guide/topics/ui/menus.html#options-menu

like image 35
nedaRM Avatar answered Sep 23 '22 05:09

nedaRM