I have an activity that on it's onCreate method it does:
registerForContextMenu(theView);
and in onCreateContextMenu:
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(blablabla);
This works great, but the problem is that t开发者_如何学JAVAhe context menu disappears when the screen rotates. How to fix this?
Thanks for reading!
Here's the solution:
The contextMenu disappeared because by default when rotating android calls destroy() and then onCreate() but :
If you don't want Android to go through the normal activity destroy-and-recreate process; instead, you want to handle recreating the views yourself, you can use the android:configChanges attributes on the element in AndroidManifest.xml.
<activity
android:name=".SmsPopupActivity"
android:theme="@android:style/Theme.Dialog"
android:launchMode="singleTask"
android:configChanges="orientation|keyboardHidden"
android:taskAffinity="net.everythingandroid.smspopup.popup">
</activity>
This way my contextMenu is not closed when my phone rotates, because onCreate() method is not called.
See also:
- Developing Orientation-Aware Android Applications
- activity-restart-on-rotation-android
According to the Android developers blog:
The Activity class has a special method called onRetainNonConfigurationInstance(). This method can be used to pass an arbitrary object your future self and Android is smart enough to call this method only when needed. [...] The implementation can be summarized like so:
@Override public Object
onRetainNonConfigurationInstance() {
final LoadedPhoto[] list = new LoadedPhoto[numberOfPhotos];
keepPhotos(list);
return list; }
In the new activity, in onCreate(), all you have to do to get your object back is to call getLastNonConfigurationInstance(). In Photostream, this method is invoked and if the returned value is not null, the grid is loaded with the list of photos from the previous activity:
http://android-developers.blogspot.com/2009/02/faster-screen-orientation-change.html?utm_source=eddie
I may be wrong, but from what I know you cant persist it, however (this is the part where i may be wrong in) you could open the menu dynamically after you rotate. Giving the illusion of persistence.
精彩评论