Menu Items are not showing on Action Bar

2019-01-07 05:50发布

问题:

I have made a completely new project. I have added items to the menu layout file. Those items do not show up on the action bar's right side. I remember that an icon with three dots shows up which opens up the menu.

Here is my Activity

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ActionBar actionBar = getActionBar();
        actionBar.setBackgroundDrawable(new ColorDrawable(Color.BLUE));     
        actionBar.show();
    }

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

}

And here is my main.xml

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

    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:showAsAction="never"
        android:title="@string/action_option1"/>
    <item
        android:id="@+id/action_settings34"
        android:orderInCategory="100"
        android:showAsAction="never"
        android:title="@string/action_option2"/>
    <item
        android:id="@+id/action_settings3"
        android:orderInCategory="100"
        android:showAsAction="never"
        android:title="@string/action_option3"/>


</menu>

回答1:

Since you set the showAsAction attribute to never, then these menu items will never show as action views. Try this:

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

    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:showAsAction="ifRoom|withText"
        android:title="@string/action_option1"/>
    <item
        android:id="@+id/action_settings34"
        android:orderInCategory="100"
        android:showAsAction="ifRoom|withText"
        android:title="@string/action_option2"/>
    <item
        android:id="@+id/action_settings3"
        android:orderInCategory="100"
        android:showAsAction="ifRoom|withText"
        android:title="@string/action_option3"/>

</menu>


回答2:

Context

There seems to be a misunderstanding about this showAsAction property in the menu configuration. The information I find in the many stackoverflow answers always seem to be incomplete. So here is an attempt to change that.

Three dot | overflow | options menu

There is no way to control if your actionbar will show the three dot overflow menu or not in code.

Well you can force it not to show by having no options menu for sure. And to be fair you can hack around this, more info at How to force use of overflow menu on devices with menu button

The dots showing or not depends on the device you're testing on. Devices with a menu button will NOT SHOW the three dot icon on the actionbar since users can use the menu button on the device.

Devices that don't have this options menu button (like the nexus devices starting from Galaxy) have no alternative to trigger that options menu. Running the same app on these devices will show the three dot overflow menu option in the actionbar.

What you can control

There is the showAsAction option in the menu xml file that you can use to control how that single menu option will show up in the actionbar.

According to official menu resource doc the options are:

android:showAsAction=["ifRoom" | "never" | "withText" | "always" | "collapseActionView"]

The ifRoom flag only shows the option if there is enough room. This should be your first choice in most cases. This will however condense the title in the actionbar (see vertical oriented screenshot).

The never flag will have this option always in the overflow menu and never directly in the actionbar.

The use of the always flag is discouraged since it will force the option to always appear in the acitonbar. Even if running on a very small screen size. This could render the title completely invisible.

As you might now an option menu can have both an android:title and an android:icon property. You can use the withText flag together with always or ifRoom (use a pipe | in between) to force the text of the item to show next to the icon when rendered in the actionbar.

The collapseActionView is only supported from API level 14 so let me ignore that.

A screenshot showing the below code snippet in action on a device hold in portrait mode:

And another screenshot where there is more space in the actionbar thanks to the landscape mode:

Android Documentation

The best development doc about this actionbar would be the actionbar guide. If you're looking more for design guidelines follow this link. The menu resource link was listed before. For menus in general check this.

Code snippet

The code only for reference since that part seems to be right in most answers. A more complete example can be found at https://github.com/AndroidExamples/fragment-navigation

The /res/menu/main.xml file contents:

<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="be.hcpl.android.example.MainActivity" >

<!-- an option that never appears as a fixed text/icon in the actionbar -->
<item android:id="@+id/action_one"
    android:title="@string/action_one"
    android:orderInCategory="100"
    app:showAsAction="never" />

<!-- another option that only appears if there is enough room -->
<item android:id="@+id/action_two"
    android:title="@string/action_two"
    android:orderInCategory="200"
    app:showAsAction="ifRoom" />

<!-- a last option that always appears -->
<item android:id="@+id/action_three"
    android:title="@string/action_three"
    android:orderInCategory="300"
    app:showAsAction="always" />

<!-- an option to show with both icon and text -->
<item android:id="@+id/action_four"
    android:icon="@android:drawable/ic_menu_directions"
    android:title="@string/action_four"
    android:orderInCategory="400"
    app:showAsAction="withText|always" />

<!-- an option to always show as an icon only -->
<item android:id="@+id/action_five"
    android:icon="@android:drawable/ic_menu_info_details"
    android:title="@string/action_five"
    android:orderInCategory="500"
    app:showAsAction="always" />

</menu>

Some linked answers

  • Action buttons doesn't show up on Action Bar?
  • Actionbar not shown with AppCompat
  • Android - want to show 3-dots menu on ICS


回答3:

I think you want to show the overflow menu icon on the top right always and want your menu to open from there. Try something like following to force it there:

Inside your onCreate() do:

  try {
        ViewConfiguration config = ViewConfiguration.get(this);
        Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
        if(menuKeyField != null) {
            menuKeyField.setAccessible(true);
            menuKeyField.setBoolean(config, false);
        }
    } catch (Exception ex) {
        // Ignore
    }

It will force the App to show the overflow menu. The menu button will still work, but it will open the menu in the top right corner. Taken from this answer at How to force use of overflow menu on devices with menu button . This might be a kind of 'hack' but it works.

Edit:

Based on useful comments from @gunar, I request not to use this method. Following are the reasons:

  • The private field sHasPermanentMenuKeycan be refactored in a future releases. Your app will stop working then.

  • Also If you force moving action items to action bar because you're used to them, you'll end up confusing users that are used to how apps run on their device. Those with hardware menu key will be used to have the options showed from menu hardware key. If you intentionally show them the three dots of overflow menu, it might confuse them.

So let all the apps be uniform in that sense. Those devices with no hardware key for menu items will show those automatically.



回答4:

OR you could create a structure like:

<?xml version="1.0" encoding="utf-8"?>
<menu >
<item
    android:id="@+id/menu_main"
    android:icon="@drawable/icon_menu"
    android:showAsAction="always"
    android:title="@string/menu_A"
    android:visible="true">
    <menu>
        <item
            android:id="@+id/menu_settings1"
            android:showAsAction="never"
            android:title="@string/menu_A1"/>
        <item
            android:id="@+id/menu_settings2"
            android:showAsAction="never"
            android:title="@string/menu_A2"/>
        <item
            android:id="@+id/menu_settings3"
            android:showAsAction="never"
            android:title="@string/menu_A3"/>
    </menu>
</item>
</menu>

Where the icon_menu you can create a new icon set with the three points icon clipart.



回答5:

I had the same problem. And I did all of the things that were said above. My problem was I forgot to override onCreateoptionMenu(Menu menu).

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


回答6:

Add

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

in the onCreate method.



回答7:

After searching and reading a lot of answer, I found that there is another little thing that you should pay attention to.

At least it was my problem and I didn't find an answer of any above. On your .XML file. Your android:showAsAction= shouldn't be form android package, it should be from app package like in the example below:

app:showAsAction=

Don't forget to import the app package.



回答8:

all answers above explained this issue well

but can we override this limitation and have the overflow menu item?!!

yes we can hack

 private void makeActionOverflowMenuShown() {
    //devices with hardware menu button (e.g. Samsung Note) don't show action overflow menu
    try {
        ViewConfiguration config = ViewConfiguration.get(this);
        Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
        if (menuKeyField != null) {
            menuKeyField.setAccessible(true);
            menuKeyField.setBoolean(config, false);
        }
    } catch (Exception e) {
        Log.d(TAG, e.getLocalizedMessage());
    }
}

and inside onCreate call it

references: https://stackoverflow.com/a/13098824/4251431



回答9:

You need to call this function in onCreate function of the activity.

RequestWindowFeature (Window.FEATURE_ACTION_BAR);


回答10:

add custom namespace like this to showAsAction and actionViewClass

<menu xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="@+id/search"
    android:title="@string/search"
    android:icon="@drawable/ic_search"
    app:showAsAction="collapseActionView|ifRoom"
    app:actionViewClass="android.widget.SearchView" />


回答11:

What worked for me was changing a property in menu.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:id="@+id/gamingactivity_filter" android:showAsAction="ifRoom"   android:icon="@drawable/ic_filter"/> 

this used to work in Material theme but didn't for AppCompat Theme & Activity so i changed how my menu.xml and add app:showAsAction= property under namespace `"http://schemas.android.com/apk/res-auto"

<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto">
  <item android:id="@+id/gamingactivity_filter" android:showAsAction="ifRoom"  app:showAsAction="ifRoom" android:icon="@drawable/ic_filter"/>

from actvity inflate menu through OnCreateOptionsMenu(IMenu menu) and now from OnOptionsItemSelected() i can also get the selected item id as

 public override bool OnOptionsItemSelected(IMenuItem item)
        {
                switch (item.ItemId)
                {
                    case Resource.Id.gamingactivity_filter:
                        OnBackPressed();
                        break;
                }
            }
            return true;
        }