Kar
Kar

Reputation: 6345

How to display the 3-dots menu without using Action Bar?

Suppose my app doesn't use the Action Bar, does anyone know how I could show the 3-dots option menu when the current device hasn't got a hardware menu button? I've seen code snippets like that below, but it's for use with Action Bar, right?

<!-- list_menu.xml -->
?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:id="@+id/menu_item_1"
        android:title="@string/menu_string_1" 
        android:showAsAction="ifRoom|withText"/>
    <item android:id="@+id/menu_item_1"
        android:title="@string/menu_string_2" 
        android:showAsAction="ifRoom|withText"/>
</menu>

In the onCreateOptionsMenu:

public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater mi = getMenuInflater();
    mi.inflate(R.menu.list_menu, menu);
    return true;
}

Thanks!

Upvotes: 1

Views: 8031

Answers (3)

Kaschwenk
Kaschwenk

Reputation: 622

Just to clear things up: You dont want an action bar in your app. If the device has a hardware menu button, you don't want to show the overflow icon (the three dots). And if the device has no hardware menu button, you want to show an seperate overflow, right?

You can check for a hardware menu button with

ViewConfiguration.get(getApplicationContext()).hasPermanentMenuKey();

You can use the following code to put a listener to this button:

@Override
public boolean onKeyDown(int keycode, KeyEvent e) {
    switch(keycode) {
        case KeyEvent.KEYCODE_MENU:
            doSomething();
            return true;
    }

    return super.onKeyDown(keycode, e);
}

It won't matter if the device doesn't have a hardware menu button so you can insert this method in any case.

That deals with the case that the phone has the button. If it has no hardware button you have to programmatically add one in the onCreate() method of your activity. So you would write something like this in onCreate():

LinearLayout layout = (LinearLayout) findViewById(R.id.linear_layout);
if(!ViewConfiguration.get(getApplicationContext()).hasPermanentMenuKey()) {
    Button overflowButton = new Button(this);

    // Add further parameters to the button
    // Especially the position (upper right) and the icon (overflow)

    layout.addView(overflowButton );
}

The overflow icon can be downloaded here: https://developer.android.com/design/downloads/index.html (its in the action bar icon pack).

Hope this helps :)

Upvotes: 3

John
John

Reputation: 8946

You can check whether the hardware menu key is present or not in the device using

ViewConfiguration.get(context).hasPermanentMenuKey()

And show your icon based on that

Upvotes: 0

fida1989
fida1989

Reputation: 3249

The menu appears in the ActionBar with >=3.0 devices. Without actionbar it won't work. For older <3.0 devices you can use ActioBarSherlock library to create ActionBar.

Upvotes: 0

Related Questions