使用工具栏作为操作栏时不会填充菜单。

4
我正在尝试将工具栏用作操作栏,并遵循Chris Banes的指南:https://chris.banes.me/2014/10/17/appcompat-v21/。现在按照该设置,我有一个空的工具栏,似乎getMenuInflater().inflate()不起作用。在我的活动中,我有:
@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menuhome, menu);
        [...]

在 onCreate() 中:

Toolbar toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
setSupportActionBar(toolbar);

这是我的布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:allmytv="http://schemas.android.com/apk/res-auto"
    xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
    android:id="@+id/linearlayoutmain"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <android.support.v7.widget.Toolbar
        xmlns:allmytv="http://schemas.android.com/apk/res-auto"
        android:id="@+id/my_awesome_toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary" />

    <com.astuetz.PagerSlidingTabStrip
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="48dip"
        allmytv:pstsIndicatorColor="#f57c1d" />

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="1" >
    </android.support.v4.view.ViewPager>


</LinearLayout>

我错在哪里?
2个回答

5
为了将工具栏用作操作栏,您需要将属性windowActionBar设置为false。
在styles.xml中包含以下内容。
<style name="AppCompatTheme" parent="@style/Theme.AppCompat.Light.NoActionBar">
        <item name="windowActionBar">false</item> 
        <item name="colorPrimary">#4285F6</item>
    </style>

在manifest.xml文件中,在标签下使用上述主题。
android:theme="@style/AppCompatTheme"

我使用工具栏来展开菜单:

 toolbar.inflateMenu(R.menu.your_toolbar_menu);

很不幸,即使使用您提出的更改,我的工具栏仍然是空的! - Giuseppe
你可以通过toolbar.setTitle("ToolBar")来设置标题,然后检查标题是否可见。 - kunal.c
不需要为主题指定“NoActionBar”。可以通过调用“setSupportActionBar(toolbar)”同时使用工具栏和操作栏。 - IgorGanapolsky

2
这是一个非常具体的问题。问题在于我设置了一个闪屏,代码如下:
setContentView(R.layout.splashhome);

工具栏为空是因为我在启动屏幕活动时调用了setSupportActionBar(toolbar)。

将setSupportActionBar(toolbar)移动到正确的位置即可解决问题!


调用 setSupportActionBar(toolbar) 的唯一前提条件应该是一个非空的工具栏... - IgorGanapolsky

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接