【问题标题】:Android Toolbar Menu items not showing when I have当我有 Android 工具栏菜单项时未显示
【发布时间】:2016-05-14 23:10:37
【问题描述】:

我有一个ImageButton,以及在我的android.support.v7.widget.Toolbar 中定义的TextView。我也有一个菜单项,但是当我运行应用程序时它没有显示出来。

我已经在我的活动中找到了getMenuInflater().inflate(R.menu.menu, menu),但不确定我在这里缺少什么。

这是我的tool_bar.xml

<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="80dp"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:background="@color/colorPrimary"
    android:id="@+id/tool_bar">

    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_nav_icon"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/app_name"
        android:textSize="30dp"
        android:layout_marginLeft="20dp"
        android:textColor="#ffffff"/>

</android.support.v7.widget.Toolbar>

这是我的菜单项:

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

    <item
        android:icon="    @drawable/ic_search"
        android:title="Search"
        app:showAsAction="always" />

</menu>

这是我的HomeActivity.java 课程

private Toolbar toolbar;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);

    toolbar = (Toolbar)findViewById(R.id.tool_bar);
    this.setSupportActionBar(toolbar);
}

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

@Override
public boolean onOptionsItemSelected(MenuItem menuItem)
{
    //implement logic here to get selected item
    return super.onOptionsItemSelected(menuItem);
}

为什么菜单项不显示?

【问题讨论】:

  • 试试这个,但我不确定在你的工具栏中添加主题 android:theme="@android:style/ThemeOverlay.Material.Dark.ActionBar"
  • 这需要 API 级别 21
  • 我已经将上面的主题添加到我的样式文件中,并将工具栏的样式设置为这个,仍然没有解决。
  • 我认为问题在于您的menu.xml 文件的位置。它应该在/res/menu/menu.xml

标签: android android-layout android-studio


【解决方案1】:

试试这个, 在 home.xml 中添加此代码

<include android:id="@+id/tool_bar" layout="@layout/tool_bar"></include>

风格也变了

 <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">

【讨论】:

  • 这正是我的代码的样子,好吧,没有 ID,但我还是复制了你的解决方案,我意识到我在包含中的 ID 没有设置。我会将其标记为解决方案,因为您基本上确实解决了我的问题;-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多