简体   繁体   中英

How do i set up the Android Back-Button (Java)?

So I got 2 States: a menu-state and a play-state .

If I'm in the play-state and click the android back-button , then it exits the app. But I want the back-button to turn me back to menu state instead.

How do I set that up? OnBackPressed is not working, because i do not have an Activity .

Instead I tried to set it up like this in the play-state :

@Override
public void handleInput() {
        if (Gdx.input.isKeyPressed(Input.Keys.BACK)){
            gsm.set(new MenuState(gsm));
        }
}

It's kinda working, but not the way that I want it. So if I click the back-button now, then it goes to the menu-state but kinda loops between Play-State and Menu-State and then exits the app. But when I hold the back-button and let it go after like 3 seconds, then I'm in the K and it stays there, like i want it.

handleInput() is also being updated all the time.

I hope you guys could help me, since it's really important to me and I tried to fix it for hours.

I will answer questions fast.

Thanks.

Android activities are stored in the activity stack. If you want to go one activity back you can use something like this:

    @Override
public void onBackPressed() {
    super.onBackPressed();
    finish();
}

This is going to finish your current activity and gets you back to your last activiy.

But if you already finished your last activity wich is firstactivity you need to start it again. Wich means you need to put it this way:

    Intent first_intent = new Intent(getApplication(), First_Activity.class);
            startActivity(first_intent);
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        //Logic you want here
        return true;
    } else {
        return super.onKeyDown(keyCode, event);
    }
}

Have you tried implementing onKeyDown ? It may be part of the Activity superclass and you mentioned you're not using an Activity - what are you using?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM