Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Persisting a context menu after screen rotation

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!

like image 902
Macarse Avatar asked Nov 18 '25 19:11

Macarse


2 Answers

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
like image 139
Macarse Avatar answered Nov 20 '25 10:11

Macarse


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

like image 37
Eddie Avatar answered Nov 20 '25 09:11

Eddie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!