Search code examples
androidactionbarsherlockparcelableserializable

Android - Put interface in Bundle


I'm working with ActionBarSherlock, I need to change some icons on the action bar when the user does some stuff. In order to that I have to save the action bar for later usage :

private Menu actionBarMenu;

...

@Override
public boolean onCreateOptionsMenu(Menu menu)
{
    MenuInflater inflater = getSupportMenuInflater();
    inflater.inflate(R.menu.map_activity_menu, menu);
    actionBarMenu = menu;
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item)
{
    actionBarMenu.findItem(R.id.follow_my_position).setIcon(R.drawable.toolbar_myposition_active);
}

Okay ! Here's where the problems begin. When I rotate the screen, I get a NullPointerException on actionBarMenu.
I know... I didn't save it before the screen was rotated, so normally I would go to onSaveInstanceState and save my Menu there, except the actionBarMenu is an interface... More specifically, the interface com.actionbarsherlock.view.Menu and I can't modify it so that it implements Parcelable or Serializable.

So how can I save an interface in the bundle ?


Solution

  • You can't. However, you can still retain your member variable on an orientation change by adding the following code to your activity

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Object last = getLastNonConfigurationInstance();
        if (last != null && last instanceof Menu) {
            actionBarMenu = (Menu) last;
        }
    }
    
    // for FragmentActivity it is onRetainCustomNonConfigurationInstance
    public Object onRetainNonConfigurationInstance() {
        return actionBarMenu;
    };