Search code examples
androidandroid-actionbarandroid-actionbar-compatandroid-appcompat

Actionbar shows dropdown when only one item in the menu


Im using app compat theme in my app, and in the actionbar I have a menu with one item that should be shown as an icon - but instead I get menu button like this

enter image description here

Here is my code of the menu xml:

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

    <item
        android:id="@+id/action_play"
        android:icon="@drawable/play"
        android:orderInCategory="100"
        android:showAsAction="always"/>

</menu>

And here is the code on how I initialize the actionbar:

getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setTitle(title);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(false);

and show the menu:

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.names, menu);
        playStop = menu.findItem(R.id.action_play);
        return true;
    }

So can someone help me to display the menu item as it should?

Thanks


Solution

  • Using support library, android:showAsAction will not do its task. So your menu declaration is not correct. From documentation

    <menu xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:yourapp="http://schemas.android.com/apk/res-auto" >
        <item android:id="@+id/action_search"
              android:icon="@drawable/ic_action_search"
              android:title="@string/action_search"
              yourapp:showAsAction="ifRoom"  />
        ...
    </menu>
    

    If there's not enough room for the item in the action bar, it will appear in the action overflow.

    Using XML attributes from the support library

    Notice that the showAsAction attribute above uses a custom namespace defined in the tag. This is necessary when using any XML attributes defined by the support library, because these attributes do not exist in the Android framework on older devices. So you must use your own namespace as a prefix for all attributes defined by the support library.


    So your menu xml should be

    <?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto">
    
        <item
            android:id="@+id/action_play"
            android:icon="@drawable/play"
            android:orderInCategory="100"
            app:showAsAction="always"/>
    
    </menu>