设备的旋转之后恢复更改的菜单状态 [英] Restore changed menu state after rotation of a device
问题描述
我正在写的应用程序,它具有与按钮和图像的菜单。我preSS从录制单曲为停止录制按钮变为按钮和标签。问题是,当我转动我的设备,带有按钮活动得到由操作系统杀害。所以,我明白,我要救我的数据之前,它在的onSaveInstanceState
方法被杀,然后在我的的onCreate
方法。事情是这样的:
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);
}
和
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.
推荐答案
您应该将你的菜单!= NULL
块成<一个href=\"http://developer.android.com/reference/android/app/Activity.html#on$p$ppareOptionsMenu%28android.view.Menu%29\"相对=nofollow>在prepareOptionsMenu :
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.
这篇关于设备的旋转之后恢复更改的菜单状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!