How to manipulate the Activity's Options Menu

337 views Asked by At

I've Googled and come up with no code on how to manipulate what the settings button does, or what is brought up when the settings touch button on the phone is pressed.

Here is a screenshot of what I mean:

enter image description here

At the bottom, you can see that it says settings, but when I click on it, nothing happens. I want to change what happens when it is clicked.

Also, I want to be able to change what is brought up (the settings option in the screenshot is what's brought up) when the settings button on the actual phone is pressed. eg. on the S3, it's the touch button at the bottom left of your device.

Can anyone link me to a resource, or write some sample code for how to do both, or even one of the things I want to do?

1

There are 1 answers

1
Philipp Jahoda On BEST ANSWER

You need to override your Activity's onOptionsItemSelected(...) method.

Do it like this:

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    if (item.getItemId() == R.id.action_settings) { // or whatever your id is, see the .xml file
        // do something

        return true;

    } else {
        return super.onOptionsItemSelected(item);
    }
}

Check the id of the options item (e.g. settings) and do specific stuff inside the if.

In order to add more items or manipulate the Id, take a look at your projects "menu" folder and the .xml file inside it.

Here the .xml file of my main menu:

enter image description here

And how it looks inside:

(you can manipulate this file and add more actions to it that will show up in the menu)

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

    <item android:id="@+id/action_one" android:title="Action 1"></item>
    <item android:id="@+id/action_two" android:title="Action 2"></item>
    <item android:id="@+id/action_three" android:title="Action 3"></item>

</menu>

In this case my menu would have 3 Actions, and you should check for them inside your onOptionsItemSelected(...) method like that:

 if (item.getItemId() == R.id.action_one) //...

... or use switch-case. For a more detailed explanation, you can also have a look at this tutorial:

http://mobile.tutsplus.com/tutorials/android/android-sdk-implement-an-options-menu/