views:

790

answers:

3

Hi.

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 the context menu disappears when the screen rotates. How to fix this?

Thanks for reading!

A: 

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.

Faisal Abid
I tried that.There is a method called openContextMenu(view) but couldn't make it work :(
Macarse
This may be obvious, but just for sanity, are you calling openContextMenu only after calling registerForContextMenu on the view?
Klondike
yes. Tried to call it on onCreate and onResume and in boths it fails :(
Macarse
How about simulating the menu key being pressed?
Faisal Abid
@Faisal Abid: How would you do that. Remember that it isn't a common menu, it's a contextMenu that shows up when you do a long press.
Macarse
Ahh my apologizes, I thought this was the common menu. Well in that case, it changes everything. Hmm let me do some googling and test this with my app to see what i can find
Faisal Abid
+1  A: 

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:

Macarse
A: 

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

Eddie