ActivityGroup not handling back key for ListActivity

China☆狼群 提交于 2019-12-11 12:36:31

问题


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.


回答1:


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



回答2:


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




回答3:


@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.



来源:https://stackoverflow.com/questions/3822969/activitygroup-not-handling-back-key-for-listactivity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!