Android toolbar menu is not showing
Asked Answered
M

22

37

I'm trying to add a menu to the ToolBar. onCreateOptionsMenu method of my Activity is called, but no menu appears.

This is dashboard.xml (from menu folder)

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto"
      xmlns:tools="http://schemas.android.com/tools"
      tools:context="com.app.android.ui.dashboard.DashboardActivity">

    <item
        android:id="@+id/action_scan_qr"
        android:icon="@drawable/ic_drawer"
        android:title="@string/menu_scan_qr"
        app:showAsAction="always" />
</menu>

NOTE: icon of this menu is darker than the background color of the action bar, so it should be visible.

Inflating menu in Activity:

public class DashboardActivity extends ActionBarActivity {

@Override
public boolean onCreateOptionsMenu(final Menu menu) {
    getMenuInflater().inflate(R.menu.dashboard, menu);

    return true;
}

And the main theme for the application:

<style name="Theme.Application.Base" parent="Theme.AppCompat.Light">
        <item name="colorPrimary">@android:color/white</item>
        <item name="colorPrimaryDark">@android:color/white</item>
        <item name="android:windowNoTitle">true</item>
        <item name="windowActionBar">false</item>
        <item name="drawerArrowStyle">@style/Theme.Application.DrawerArrowStyle</item>
        <item name="android:textColorSecondary">@android:color/darker_gray</item>
</style>

Why onCreateOptionsMenu is called but menu doesn't appears. I'm using appcompat-v7:21.0.3

EDIT:

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getContentViewId());

        toolbar = (Toolbar) findViewById(R.id.tool_bar);
        if (toolbar == null) {
            throw new Error("Can't find tool bar, did you forget to add it in Activity layout file?");
        }

        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
    }
Mummer answered 4/2, 2015 at 9:33 Comment(5)
Try to add android:orderInCategory="100" in your xml itemBareheaded
What does your Activity's layout look like? Does it contain a Toolbar view and are you setting it to the activity via setSupportActionBar(toolbar)?Gregory
I'm using setSupportActionBar(toolbar) after inflating it from activity layout file.Mummer
Joan, orderInCategory doesn't helpMummer
Try to replace return(super.onCreateOptionsMenu(menu)); instead of return true;Bareheaded
M
35

I'm not sure why, but when I place everything related menu inflating in onCreateOptionsMenu method, everything works fine.

@Override
public boolean onCreateOptionsMenu(final Menu menu) {
    getMenuInflater().inflate(R.menu.dashboard, menu);

    return super.onCreateOptionsMenu(menu);
}
Mummer answered 4/2, 2015 at 10:9 Comment(7)
It does work indeed, but why? What is the purpose of inflate()? The official documentation doesn't even mention this.Conifer
It could be just overlapping color problem. If your toolbar is black color and the menu text is also in black color, you can't really see it. Even overflow menu icon was also black :D (It happened in my case). Further dismay- if there are only one or two menu options, even menu button does not seem to work (because menu is already present in toolbar)Adinaadine
it will continuously create when ever it is clicked,So use this @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; }Lindsey
thanks Bro it was surprisingly acting. fabulous +1 for youVinous
Do you really call super.onCreateOptionsMenu(menu) and not super.onPrepareOptionsMenu(menu)?Ribose
It will loop the options menuCocke
Should be returning "true" at the end: developer.android.com/guide/topics/ui/menus . Also the recommendation is to override onCreateOptionsMenu instead of onPrepareOptionsMenu.Skirl
F
45

I was also facing the same problem, but the actual error was, i forgot to introduce toolbar in java activity

under AppCompactActivity, under on create method define your toolbar by id and call setSupportActionBar(ToolBar);

Example is below:

public class secondActivity extends AppCompatActivity {
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        toolbar.showOverflowMenu();
Fullrigged answered 17/3, 2016 at 11:44 Comment(3)
it is correct. i had the same problem. i did you said and it solvedBenuecongo
i had everything set up but didnt use setSupportActionBar(ToolBar); introducing setSupportActionBar made the action button show upNanoid
Thanks you save my hours :)Thermopylae
M
35

I'm not sure why, but when I place everything related menu inflating in onCreateOptionsMenu method, everything works fine.

@Override
public boolean onCreateOptionsMenu(final Menu menu) {
    getMenuInflater().inflate(R.menu.dashboard, menu);

    return super.onCreateOptionsMenu(menu);
}
Mummer answered 4/2, 2015 at 10:9 Comment(7)
It does work indeed, but why? What is the purpose of inflate()? The official documentation doesn't even mention this.Conifer
It could be just overlapping color problem. If your toolbar is black color and the menu text is also in black color, you can't really see it. Even overflow menu icon was also black :D (It happened in my case). Further dismay- if there are only one or two menu options, even menu button does not seem to work (because menu is already present in toolbar)Adinaadine
it will continuously create when ever it is clicked,So use this @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; }Lindsey
thanks Bro it was surprisingly acting. fabulous +1 for youVinous
Do you really call super.onCreateOptionsMenu(menu) and not super.onPrepareOptionsMenu(menu)?Ribose
It will loop the options menuCocke
Should be returning "true" at the end: developer.android.com/guide/topics/ui/menus . Also the recommendation is to override onCreateOptionsMenu instead of onPrepareOptionsMenu.Skirl
F
11

Try the following:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:tools="http://schemas.android.com/tools"
      xmlns:app="http://schemas.android.com/apk/res-auto"
      tools:context="com.example.lolipoptest.MainActivity" >

<item
    android:id="@+id/action_settings"
    android:orderInCategory="100"
    android:showAsAction="never"
    android:title="@string/action_settings"/>
</menu>

and the Java 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;
}
Freefloating answered 4/2, 2015 at 9:45 Comment(1)
Check this one #26638589Freefloating
G
8

Do you have Toolbar in your dashboard layout ?. Call setSupportActionBar(toolbar) in your activity. Use Theme.AppCompat.NoActionBar theme for the activities (If you are using toolbar in it)

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;

public class DashboardActivity extends ActionBarActivity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
  setSupportActionBar(toolbar);
  getSupportActionBar().setDisplayHomeAsUpEnabled(true);
  getSupportActionBar().setHomeButtonEnabled(true);
}

@Override
 public boolean onCreateOptionsMenu(Menu menu) {
  getMenuInflater().inflate(R.menu.dashboard, menu);
  return super.onCreateOptionsMenu(menu);
 }

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}
}

Check your styles.

<resources>

<!-- Base application theme. -->
<style name="AppTheme.Base" parent="Theme.AppCompat.NoActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="android:windowBackground">@color/white</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

<style name="AppTheme" parent="AppTheme.Base">

</style>

<style name="ToolbarTheme" parent="AppTheme" >
</style>

<color name="light">#FFBB33</color>
<color name="colorPrimary">#FFBB33</color>
<color name="textColorPrimary">#FFBB33</color>
<color name="colorPrimaryDark">#FF8800</color>
<color name="colorAccent">#ff9977</color>
<color name="white">#ffffff</color>

</resources>

Check your layout.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minHeight="?attr/actionBarSize"
    app:titleMarginStart="20dp"
    android:paddingRight="10dp"
    android:background="@color/colorPrimaryDark"
    app:theme="@style/ToolbarTheme" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="15dp"
    android:text="Hello Toolbar" />

</LinearLayout>

Add theme in your activity in manifest

android:theme="@style/AppTheme"
Griskin answered 4/2, 2015 at 9:44 Comment(1)
Not entirely true, the library adds the toolbar if not present and the right theme is usedApocalypse
D
8

If you are inflating your menu from a fragment, e.g. by overriding onCreateOptionsMenu method, make sure to call setHasOptionsMenu(true) in onCreateView of your fragment

Donley answered 17/8, 2017 at 11:6 Comment(0)
A
6

You need to inflate your menu in onCreateOptionsMenu of the activity:

 @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.mymenu, menu);
        return super.onCreateOptionsMenu(menu);
    }
Accompanyist answered 23/6, 2017 at 14:55 Comment(1)
Should be returning "true" at the end: developer.android.com/guide/topics/ui/menusSkirl
B
3

Ensure that your toolbar initialization comes after adding the xml layout file like this:

setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar1);
setSupportActionBar(toolbar);
Bingaman answered 9/8, 2019 at 7:28 Comment(0)
F
1

Try changing:

 ....
xmlns:app="http://schemas.android.com/apk/res-auto" >
 ....
app:showAsAction="ifRoom" 

to:

 ....
xmlns:yourapp="http://schemas.android.com/apk/res-auto" >
 ....
yourapp:showAsAction="ifRoom" 

https://developer.android.com/training/basics/actionbar/adding-buttons.html

Fargone answered 4/2, 2015 at 9:54 Comment(2)
This gives me exception: "This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead."Mummer
this doesn't make sense, what is yourapp:suppose to be? the namespace app: is correctHeterolecithal
B
1

If you're using a Toolbar you need to set it as the support action bar in onCreate:

setSupportActionBar(toolbar);

But answered 19/11, 2015 at 14:45 Comment(0)
C
1

In my case it was stupid simple. My toolbar was a child of AppBarLayout, and for some reason, when I was setting a Toolbar with Constraint layout, Toolbar's layout_width xml parameter was set to 0dp. So the toolbar was there, but invisible... (>_<)

So, if nothing from above helped you, just check "layout_width" and "layout_height" parameters.

Hope this will save someone's time :)

Clackmannan answered 6/10, 2017 at 12:23 Comment(0)
U
1

Late to the answer, Hope this will save your a lot of code. You don't need to add Toolbar into the XML file if your parent theme is in the style, not a Theme.MaterialComponents.DayNight.NoActionBar , If you have Theme.MaterialComponents.DayNight.DarkActionBar as a parent in your theme.xml or style.xml, Furthermore you can add a particular theme to your activity.

Step 1: Create a menu folder under res if not exist and then create a menu item i.e item_menu

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:title="Setting"
        app:showAsAction="always"
        android:icon="@drawable/ic_baseline_settings_24"
        android:id="@+id/action_setting"/>
</menu>

STEP 2: To show the menu on the default toolbar, add the below method in your activity

//To show or inflate menu on the toolbar
    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.item_menu, menu)
        return true
    }

Step 3: To handle click events, add the below method.

//Handle the click event on the menu item option
    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.action_setting -> {
                //DO YOUR STUFF HERE
            }
        }

        return false
    }

NOTE: YOU DON'T NEED TO ADD A TOOLBAR INTO THE XML FILE.

Ulm answered 23/11, 2021 at 17:25 Comment(0)
H
1

Another place to check that can disable the action bar is your themes. By default in Android Studio it gives you the Material3 light theme that does not support action bars. Replace that theme with one that does. You'll be able to find the folder at:

res/values/themes/themes.xml

Next in the file it should be on the same line as the:

<style name="Base.Theme.<AppName>" parent="<Material3 or other theme that disables action bar>">

And just replace the parent theme with one that does support action bars.

Hotel answered 24/10, 2023 at 20:8 Comment(0)
P
0

The issue is resolved when I changed it to app:showAsAction to android:showAsAction

Polack answered 2/7, 2017 at 23:21 Comment(1)
nope, when you do this, and error will be show you.Bent
N
0

Add Icon you want under mipmap folder

ic_menu_options

Create menu_analysis.xml(under menu folder values.xml)

 <?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.app.android.ui.dashboard.DashboardActivity">
         <item
            android:id="@+id/action_scan_qr"
            android:icon="@mipmap/ic_menu_options"
            android:title=""
            app:showAsAction="always" />
</menu>

Now onPrepareOptionMenu under your Java class

@Override
public boolean onPrepareOptionsMenu(final Menu menu) {
    getMenuInflater().inflate(R.menu.menu_analysis, menu);
    return super.onCreateOptionsMenu(menu);
}
Northcutt answered 30/10, 2017 at 5:51 Comment(0)
A
0

Although the accepted answer does work, it causes my menu items rendered twice. As I've just worked around this, try somethings as:

  1. remember to return true; instead of super.onCreateOptionsMenu(menu);
  2. remember to set support action bar setSupportActionBar(findViewById(R.id.toolbar))
  3. You might want to turn off default app title if you use customized toolbar: getSupportActionBar().setDisplayShowTitleEnabled(false)
Afterbrain answered 17/5, 2018 at 20:5 Comment(0)
R
0

Use setSupportActionBar(toolbar) in onCreate Method.

Resentment answered 17/8, 2018 at 6:21 Comment(1)
kindly consider adding more information in your answerMelainemelamed
K
0

I had written like,

MenuInflater(this).inflate(R.menu.my_menu, menu)

But, I changed the code like,

menuInflater.inflate(R.menu.my_menu, menu)

and it worked!

(I'm using kotlin and this code was written in Activity)

Kirima answered 9/11, 2018 at 7:50 Comment(0)
L
0

Using XML Code

app:menu="menu_name"

Using java code

     public class MainActivity extends AppCompatActivity { 
        
          private Toolbar toolbar;
        
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);
                toolbar = findViewById(R.id.toolbar);
                setSupportActionBar(toolbar);
        }

@Override
    public boolean onCreateOptionsMenu(Menu menu) 
        getMenuInflater().inflate(R.menu.demo_menu,menu);
        return super.onCreateOptionsMenu(menu);
    }
  }

Full article on adding navigation icon , subtitle ,title , brand logo to the toolbar you must go through https://bedevelopers.tech/android-toolbar-implementation-using-android-studio/

Lutenist answered 24/11, 2020 at 16:40 Comment(0)
H
0

If nothing works then try the following :

Add following line in onCreateView() method

setHasOptionsMenu(true)

Also add below line in onViewCreated() method

(activity as AppCompatActivity?)!!.setSupportActionBar(customToolbar as Toolbar?)

Where customToolBar is the id of the toolbar added in xml file

Hardeman answered 18/1, 2022 at 14:44 Comment(0)
S
0

Overwriting onCreateOptionsMenu fixes the issue, but when you want to inject a different menu into Fragments then in the Activity, the onCreateOptionsMenu() and onPrepareOptionsMenu() methods are Deprecated there.

Instead, implement the new MenuProvider interface and link this menu provider in the Activity with addMenuProvider() and add a different MenuProvider in the Fragment:


class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        ...
        setSupportActionBar(findViewById(R.id.toolbar))
        addMenuProvider(MenuProvider())
    }

    private class MenuProvider : androidx.core.view.MenuProvider {
        override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
            menuInflater.inflate(R.menu.fragment1, menu)
        }

        override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
            TODO("Not yet implemented")
        }
    }
}

Fragment

 override fun onViewCreated(view: View, savedInstanceState: Bundle?) {

    val menuHost: MenuHost = requireActivity()
        menuHost.addMenuProvider(object : MenuProvider {
            override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
                menuInflater.inflate(R.menu.trips, menu)
            }

            override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
                TODO("Not yet implemented")
            }
        }, viewLifecycleOwner, Lifecycle.State.RESUMED)

    ...

 }
Sulemasulf answered 13/2, 2023 at 13:56 Comment(0)
F
0

In my case it was overlapping of views, and click get over by another view. (ps. Check xml closely)

Falk answered 28/2, 2023 at 9:30 Comment(0)
A
-1

Just try this under onCreate:

toolbar.inflateMenu(R.menu.menu);
Allround answered 26/2, 2020 at 9:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.