菜单未显示在自定义工具栏中

Menu is not showing in custom toolbar

我正在尝试在我的 android 应用程序中使用自定义菜单。我想添加一些菜单项。 为此,我在 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>

并且在 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);
    }

但是,它根本不起作用。 我在 SO 上尝试了一些解决方案,但其中 none 有效。

例如this

请帮我解决这个问题。

您必须将工具栏设置为

setActionBar(toolbar);

在 onCreate() 中