Menu is not showing in custom toolbar

1.1k views Asked by At

I am trying to use custom menu in my android app. I want to add some menu items. For the purpose, I add following in my menu_main.xml:

<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=".MainActivity">
    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:title="@string/action_settings"
        app:showAsAction="always" />

    <item
        android:id="@+id/contact"
        android:icon="@drawable/ic_star"
        android:orderInCategory="2000"
        android:title="@string/Rate"
        app:showAsAction="always" />
</menu>

And in MainActivity:

  @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        menu.clear();
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings)
        {
            Toast.makeText(this,"Hello from settings",Toast.LENGTH_LONG).show();
            return true;

        }
        if ( id == R.id.contact)
        {
            startActivity(new Intent(this,ContactUs.class));
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

But, it is not working at all. I tried some solutions on SO, but none of them worked.

e.g. this

Please help me to solve this.

1

There are 1 answers

2
Muthukrishnan Suresh On BEST ANSWER

You have to set your toolbar like

setActionBar(toolbar);

in onCreate()