Restore changed menu state after rotation of a device

混江龙づ霸主 提交于 2019-12-11 14:02:21

问题


I'm writing an application, which has a menu with buttons and an image. I press the button and label of the button changes from "Record track" to "Stop recording". The issue is when I rotate my device, the activity with buttons gets killed by the OS. So, I understood that I have to save my data before it's get killed in onSaveInstanceState method and then restore it in my onCreate method. Something like this:

@Override
public void onSaveInstanceState(final Bundle saveInstanceState) {
    saveInstanceState.putSerializable("image", image);
    saveInstanceState.putSerializable("buttonState", isRecording);

}

And:

if (savedInstanceState != null) {                                
    isRecording = savedInstanceState.getBoolean("buttonState");  

    if (menu != null) {                                          
        MenuItem recordButton = menu.getItem(R.id.track);

        if (!isRecording) {
            recordButton.setTitle(R.string.rec_track_label);     
        } else {
            recordButton.setTitle(R.string.stop_rec_track_label);
        }
    }                                                            

    Image = (Image)savedInstanceState.getSerializable("image");

} 

And while it perfectly restores my image, I still have issues with the menu: for some reason it always stays "null", so it will never change label of my button despite that it should be recreated every time, when Activity starts and I save it in a private object of my Activity:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    new MenuInflater(this).inflate(R.menu.actions, menu);
    this.menu = menu;
    return (super.onCreateOptionsMenu(menu));
}

Any ideas what am I doing wrong? Thanks.


回答1:


You should move your menu != null block into onPrepareOptionsMenu:

public boolean onPrepareOptionsMenu(Menu menu)
{
    MenuItem recordButton = menu.findItem(R.id.track);

    if (isRecording) {
        recordButton.setTitle(R.string.rec_track_label);     
    } else {
        recordButton.setTitle(R.string.stop_rec_track_label);
    }
}

As this method is called directly before the menu is being shown to the user.



来源:https://stackoverflow.com/questions/15992598/restore-changed-menu-state-after-rotation-of-a-device

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!