Ambran
Ambran

Reputation: 2617

Android: Can't toggle MenuItem icon

I'm tring to change a menuitem icon, but the icon is not being changed.

Here is how I find the MenuItem (works fine):

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu items for use in the action bar
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.activity_location_actions, menu);
    mActionLocation = menu.findItem(R.id.action_location);
    return super.onCreateOptionsMenu(menu);
}

Method UpdateIcon: I took a screenshot so you can see (in the red frame) that the images have been found by the system.

enter image description here

The mActionLocation is a MenuItem which is initialized before this Method is called and is not null.

Anyone has an idea?


UPDATE (solution by help from @vinitius)

The UpdateIcon method:

private void UpdateIcon(boolean locationOn) {
    mActionLocation = locationOn; // mActionLocation is a global boolean
    invalidateOptionsMenu();
}

The onPrepareOptionsMenu override:

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    // Toggle location icon
    if (mActionLocation) {
        menu.findItem(R.id.action_location).setIcon(R.drawable.ic_location_on_white_24dp);
    } else {
        menu.findItem(R.id.action_location).setIcon(R.drawable.ic_location_off_white_24dp);
    }
    return super.onPrepareOptionsMenu(menu);
}

Upvotes: 0

Views: 773

Answers (1)

vinitius
vinitius

Reputation: 3274

You need to use onPrepareOptionsMenu(Menu menu):

This is called right before the menu is shown, every time it is shown.You can use this method to efficiently enable/disable items or otherwise dynamically modify the contents.

Inside this method, retrieve your item as you do in onCreateOtionsMenu and check whether your gps in os or not to modify your item icon.

Upvotes: 1

Related Questions