user3797031
user3797031

Reputation: 51

How to properly display a menuitem?

I'm trying to create some MenuItems, this way:

main_activity_actions.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/item_add"
        android:icon="@drawable/ic_action_add"
        android:orderInCategory="1"
        android:title="@string/action_add"
        android:showAsAction="always" />
    <item
        android:id="@+id/item_settings"
        android:orderInCategory="2"
        android:title="@string/action_settings"
        android:showAsAction="never" />
    <item
        android:id="@+id/item_about"
        android:orderInCategory="3"
        android:title="@string/action_about"
        android:showAsAction="never" />
</menu>

MainActivity.java

@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_activity_actions, menu);
    return super.onCreateOptionsMenu(menu);
}

I cannot get the render of those items on the top menu bar. How do I to make this work, please ?

Thanks in advance!

Upvotes: 1

Views: 47

Answers (1)

joao2fast4u
joao2fast4u

Reputation: 6892

I figured it out. With android support library v7 appcompat, you have to use a specific namespace to use the attribute showAsAction correctly. Here is what you need to do on your xml file:

Add your custom namespace declaration to the file like this:

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

Then instead of using android:showAsAction, use app:showAsAction.

This will allow the menu items to show.

Here's the result file code:

<?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/item_add"
        android:icon="@drawable/ic_action_add"
        android:orderInCategory="1"
        android:title="@string/action_add"
        app:showAsAction="always" />
    <item
        android:id="@+id/item_settings"
        android:orderInCategory="2"
        android:title="@string/action_settings"
        app:showAsAction="never" />
    <item
        android:id="@+id/item_about"
        android:orderInCategory="3"
        android:title="@string/action_about"
        app:showAsAction="never" />
</menu>

Hope I have helped you.

Upvotes: 1

Related Questions