define Action bar overflow items

2019-05-01 02:38发布

问题:

If I define the following items for my action bar:

res/menu/action_menu.xml :

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:title="label"/>
    <item android:title="label1"/>
    <item android:title="label2"/>
    <item android:title="label3"/>
    <item android:title="label4"/>

</menu>

In my Activity:

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

Is there anyway to allow me define certain items move to action overflow part ? and how to do it?

P.S. Action overflow part is the right-most part of action bar which hide certain items like a popup menu.

回答1:

It's the other way round. You need to explicitly tell the menu which ones you want in the ActionBar and which not by setting the appropriate flags

E.g.

<item android:id="@+id/refresh"
      android:title="@string/refresh"
      android:icon="@drawable/reload_button"
      android:showAsAction="always"/>

Here android:showAsAction tells how to handle it. Options are

  • always
  • ifRoom
  • never
  • withText

You can or options together with the pipe symbol as "always|withText"

See the android docs for action bar for more documentation.



回答2:

To add something to Heiko's answer about the "overflow menu" on the action bar, this only happens if you have items set as ifRoom and there is no room for them to be displayed. On the overflow menu they only appear with a title and no icon.

On Android 4.0, the overflow menu ("3 dot spinner") is only shown on devices that don't have the physical "menu" button. You can test this on an ADV setting the option Hardware Back/Home keys option to "no".