开发者

Manage the back button with multiple scene

I followed this tutorial http://www.andengine.org/forums/tutorials/multiple-screen-andengine-game-v2-t4755.html to create a simple application with multiple scene and only one activity. I'd like to know how can i can return to the previous scene when i use the back button and finish the activity when i'm in the first scene.

I tried so in the MultiScreen Class:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ((keyCode == K开发者_如何学JAVAeyEvent.KEYCODE_BACK)) {
        this.mEngine.getScene().back();
    }
    return super.onKeyDown(keyCode, event);
}

replacing the core.getEngine().setScene(scene); in the SceneManager with this.mEngine.getScene().setChildScene(scene);


scene work differently from how I understood, I resolve with:

    @Override
    public void onBackPressed()
    {
        Scene scene = this.mEngine.getScene();
        if(scene.hasChildScene()){
            scene.back();
        }
        else{
            this.finish();
        }
    }


You can override the back key in one of two ways, either by overriding the onBackPressed() method, or the dispatchKeyEvent() method

Overriding onBackPressed:

@Override
public void onBackPressed()
{
    // your code here
}

Overriding dispatchKeyEvent:

@Override
public boolean dispatchKeyEvent(KeyEvent event)
{
    if (keyCode == KeyEvent.KEYCODE_BACK)
    {
        // your code here
    }
    return (yourbooleanhere);
}


I had a dilemma like you in that sense. I explain. I have an activity like works with a ViewFlipper. I need to go to the different "layout" that I wrote on ViewFlipper tag and, when a I was in a particular "layout" that is not the main "layout" of the activity, I need to come back to the main pressing the back button, but, it doesn't work what I want.

To resolve this dilema, I override OnBackPressed function like:

@Override
public void onBackPressed() {
    if (condition) {
        // go to the main 
    } else {
        super.onBackPressed();
}
}

where condition, as name says, how do you know that you are in the main "layout"? For example, in my ViewFlipper, the main "layout" are ordered by numbers, that begin on 0, so my main "layout" is 0 and how I know that I am in the 0 "layout", viewflipper.getDisplayedChild(). If it returns 0, I stay in the main "layout" or not, otherwise.

So simple but, I know, not so elegant. It's an idea, I think that can help you.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜