Search code examples
javaandroidxmloverflow-menu

How to change menu overflow button programmatically?


So I have a overflow menu button in the view which I have converted into an edit button. Here is the XML code for the button:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context=".HomeActivity">
    <item android:id="@+id/action_edit"
        android:title="Edit"
        android:icon="@drawable/editbutton"
        app:showAsAction="always"/>
</menu>

I have also created a java function on edit button pressed as below:

public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.action_edit:
            floatIn.start();
            fabImageButton.setTranslationX(-1 * fabOffset);
            populateAnimators();
            openAnimSet.start();
            return true;
    }

    return super.onOptionsItemSelected(item);
}

What I want to do is when the edit button is pressed, inside the case statement within the onOptionsItemSelected is to change the drawable of the menu button (from an edit drawable to a close drawable) and then change a property so that if the button is pressed again when the new drawable is showing, a different set of java code is triggered. I was thinking to programattically change the ID and then add another case statement? This needs to be then converted back to the original button when the close edit button is pressed.

Thanks

Kabeer


Solution

  • You can change your menu drawable by doing

    item.findItem(R.id.my_menu_item).setIcon(R.drawable.my_drawable);
    

    There are a number of ways that you could handle the change in state. Changing the id doesn't seem like the best solution though. I am handling a similar situation in my code by using an enum to track the status of the menu drawable. Here is how I handle something similar:

        public void setMenuIconState(State state) {
        switch (state) {
            case READY:
                mMenu.findItem(R.id.action_next).setIcon(R.drawable.small_arrow_green);
                mReady = true;
                break;
            case WAITING:
                mMenu.findItem(R.id.action_next).setIcon(R.drawable.small_clock_gray);
                mReady = false;
                break;
            default:
                mReady = false;
        }
    }
    

    Then, when my menu item is clicked, I'm handling it like this:

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (mReady) {
           // do some stuff
        }
        else {
            return super.onOptionsItemSelected(item);
        }
    }