Android ActionBar 菜单有问题

Having an issue with Android ActionBar menu

大家好,

我是 Android 的新手,我尝试将菜单添加到我的 Android 应用程序,如下所示:

问题是我没有在操作栏上获取菜单,我在没有图标的情况下获取它。

这是我的代码:

  public boolean onCreateOptionsMenu(Menu menu)
{
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.layout.menu, menu);
    return super.onCreateOptionsMenu(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
     switch (item.getItemId())
     {
     case R.id.chat:
        // Single menu item is selected do something
        // Ex: launching new activity/screen or show alert message
         Toast.makeText(MainActivity.this, "Chat is Selected", Toast.LENGTH_SHORT).show();
         return true;


     default:
         return super.onOptionsItemSelected(item);
     }

}

这是 xml 文件:

<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<!-- Search, should appear as action button -->
<item android:id="@+id/chat"
      android:icon="@drawable/ic_action_chat"
      android:title="action_search"
      android:showAsAction="ifRoom" />
<!-- Settings, should always be in the overflow -->

这是应用程序的屏幕截图,您可以看到菜单已关闭且没有图标:

清单:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.menu"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

将菜单 XML 文件中的 android:showAsActionandroid:showAsAction="ifRoom" 更改为 android:showAsAction="always"。那应该可以。

更新

inflater.inflate(R.layout.menu, menu); 更改为 inflater.inflate(R.menu.main, menu); 并使用菜单文件夹中的 main.xml 文件代替 layout 文件夹中的 menu.xml 文件。

更新 2

由于您在评论中提到您正在使用 appcompat 库,因此您应该按如下方式修改 menu 文件夹中的 main.xml 文件:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:compat="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools" >
<!-- Search, should appear as action button -->

<item android:id="@+id/chat"
      android:icon="@drawable/ic_action_chat"
      android:title="action_search"
      compat:showAsAction="always" />
<!-- Settings, should always be in the overflow -->

</menu>

将您的 menu 移动到菜单文件夹并按以下方式操作:

inflater.inflate(R.menu.menu, menu);