开发者

ActivityGroup not handling back key for ListActivity

开发者 https://www.devze.com 2023-01-18 06:16 出处:网络
I am using an ActivityGroup to spawn multiple activities and switch views from within the same tab in a TabActivity.

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.


In a ActivityGroup, When ListActivity is in focus onKeyDown() of ActivityGroup is not getting called, only child's (ListActivity) onKeyDown() is getting called To make sure ActivityGroup's onKeyDown() is called, We need to return false from onKeyDown() of ListActivity. After doing this change I am able to receive key events


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
    }
}


@Cristian

I am using a normal Activity instead of ListActivity, but with a ListView populated it gave me the same problem.

I only implemented onBackPressed on my Activity instead of onKeyDown to call back the same back() function that MyActivityGroup invoked.

@Override  
public void onBackPressed() {
    MyActivityGroup.group.back();  
    return;  
}

group is a static field in MyActivityGroup.

public static MyActivityGroup group; 

The back() function would be the same as yann.debonnel provided.

I don't know if this is the same case for your ListActivity, didn't test it. But in my case it worked.

0

精彩评论

暂无评论...
验证码 换一张
取 消