Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restore ActionMode after orientation change

I have listfragment which starts actionmode. I am using actionbarsherlock. But when orientation changes, or when I start new activity contextual actionbar disapears. Is there any way to restore it back, without starting it again? In google gmail app it stays on screen whether I rotate phone or go to the detail screen.

like image 632
pcu Avatar asked Aug 15 '12 05:08

pcu


People also ask

What happens when screen orientation changes in Android?

When you rotate your device and the screen changes orientation, Android usually destroys your application's existing Activities and Fragments and recreates them. Android does this so that your application can reload resources based on the new configuration.

How does the Activity respond when the user rotates the screen on an Android?

On rotation of screen, The Activity is Destroyed. The Activity is Recreated fresh in requested orientation.


1 Answers

The better way is use onSaveInstanceState to save ActionMode state before rotation.

public abstract class MyActivity extends SherlockFragmentActivity{

    private boolean isInActionMode = false;

    @Override
    public void onCreate(Bundle state){
         super.onCreate(state);

         if (state != null && state.getBoolean("ActionMode", false)){
                startActionMode(new MyActionMode());
         }else{
             ///whatever you'd normally do
         }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
         // Save isInActionMode value
         outState.putBoolean("ActionMode", isInActionMode);

         super.onSaveInstanceState(outState);
    }

    public void onWhateverEventNormallyStartsYourActionMode(){
        startActionMode(new MyActionMode());
    }

    public class MyActionMode implements ActionMode.Callback{

        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            isInActionMode = true;
            ///whatever you'd normally do
        }

        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            ///whatever you'd normally do
        }

        @Override
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            ///whatever you'd normally do
        }

        @Override
        public void onDestroyActionMode(ActionMode mode) {
            isInActionMode = false;
        }
    }
}

Updated according to Saran's comment.

like image 126
galex Avatar answered Sep 29 '22 10:09

galex