onBackPressed() not working

后端 未结 5 962
独厮守ぢ
独厮守ぢ 2021-01-07 11:05

I\'m trying to close my app on a back button click. From the main screen, the back button takes you to a credits screen. From that credits screen, I want to close the app w

相关标签:
5条回答
  • 2021-01-07 11:40

    Try the following solution?

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    
    0 讨论(0)
  • 2021-01-07 11:49

    I don't know if you have found an answer yet, but have you tried super.onBackPressed from within your overriding method?

    If I were you, I would try:

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }
    
    0 讨论(0)
  • 2021-01-07 11:50

    I don't get it. What onBackPressed() does is to call finish(). finish() is an Activity method, there's no way to "quit" your app, so to speak. Perhaps what you really want is to call finish() on the Activity that is starting the Credits activity. Inside the other activity:

       finish();
       startActivity(this, Credits.class);
    
    0 讨论(0)
  • 2021-01-07 11:53

    Sorry, i am not able to comment yet (I wanted this to be a comment on Muffinbubble's answer)..

    Try putting the onKeyDown into your mainclass and validate if this get's called even if you are in your second Activity. You could then check where you are via the main class and exit the application if needed and else return super.onKeyDown(..).

    0 讨论(0)
  • 2021-01-07 11:58

    Just recently, i ran into this issue and i was able to solve it by deleting all the folders in the build directory.

    I don't know how but it seemed that Android Studio made an error generating the build and that lead to this problem. So after deleting the build directory, myonBackpressed() method was being called.

    0 讨论(0)
提交回复
热议问题