Procurares Procurares - 6 months ago 45
Android Question

Android toolbar menu is not showing

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);
}

Answer

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

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

    return super.onCreateOptionsMenu(menu);
}
Comments