onBackPressed()不工作[英] onBackPressed() not working

本文是小编为大家收集整理的关于onBackPressed()不工作的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我正在尝试在返回按钮上关闭我的应用程序单击.从主屏幕中,后退按钮将带您到一个积分屏幕.从该学分屏幕,我想用后退按钮关闭应用程序.不幸的是,我呼唤的onback抑制()方法似乎根本没有执行.我不确定如何继续.

package app.jonward.boss;
import android.app.Activity;


public class Credits extends Activity{

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.credits);

    //Doing stuff
}


@Override
public void onBackPressed() {
   finish();
   return;
}

}

推荐答案

我没有得到它. 是什么要调用finish(). finish()是一个Activity方法,没有办法"戒掉"您的应用程序,以便说话.也许你真正想要的是在开始Credits活动的活动中调用finish().在其他活动内:

   finish();
   startActivity(this, Credits.class);

其他推荐答案

尝试以下解决方案?

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        finish();
        return true;
    }
    return super.onKeyDown(keyCode, event);
}
刚才刚才,我刚刚进入这个问题,我能够通过删除build目录中的所有文件夹来解决它.

快照删除的目录

我不知道如何,但似乎Android Studio生成构建的错误并导致这个问题.因此在删除build目录后,我的onBackpressed()方法正在调用.

本文地址:https://www.itbaoku.cn/post/102691.html

问题描述

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 with the back button. Unfortunately, the onBackPressed() method I'm calling doesn't seem to be executed at all. I'm not sure how to proceed.

package app.jonward.boss;
import android.app.Activity;


public class Credits extends Activity{

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.credits);

    //Doing stuff
}


@Override
public void onBackPressed() {
   finish();
   return;
}

}

推荐答案

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);

其他推荐答案

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

其他推荐答案

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

Snapshot of which directory to delete

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.