Search code examples
androidandroid-activitylifecycle

ActivityGroup not handling back key for ListActivity


I am using an ActivityGroup to spawn multiple activities and switch views from within the same tab in a TabActivity.

When I press the back key this method is called inside my ActivityGroup

public void back() {  
        if(history.size() > 0) {  
            history.remove(history.size()-1);
            if (history.size() > 0)
             setContentView(history.get(history.size()-1)); 
            else
              initView();
        }else {  
            finish();  
        }  
    }  

this method allows me to keep a stack of my activities and go back to the previous one when the back key is pressed.

this is working well on all my nested activities, except on a ListActivity where a press on the back key will simply exit the application.


Solution

  • I know what you mean... I faced that problem some weeks ago. I also know it's an annoying bug and I've learned the lesson: I won't use that approach ever! So, basically, in order to fix this you will have to do some workarounds to your code. For instance, I fixed that problem with one of my activities adding this code to the activity:

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && StatsGroupActivity.self != null) {
            StatsGroupActivity.self.popView();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    

    Notice that my ActivityGroup is called StatsGroupActivity and looks like:

    public class StatsGroupActivity extends GroupActivity{
    
        /**
         * Self reference to this group activity
         */
        public static StatsGroupActivity self;
    
        public void onCreate(Bundle icicle){
            super.onCreate(icicle);
            self = this;
            // more stuff
        }
    }