在同一 activity 中按下后退按钮的正确实现是什么?

What is the proper implementation of the back button press in same activity?

我想检测后退按钮。 但是,我当前的实现甚至没有检测到后退按钮。

代码:

   @Override
    public boolean onTouch(MotionEvent e, int scaledX, int scaledY) {

        //... OTHER CODE ...
        else if(e.getAction() == MotionEvent.BUTTON_BACK){
            System.out.println("BACK BUTTON PRESSED");
            setCurrentState(new MenuState());
        }
        return true;
    }
}

您可以在 Activity:

中使用 onBackPressed()
@Override
public void onBackPressed() {
    //Do something
}

文档里写的:

public static final int BUTTON_BACK
Button constant: Back button pressed (mouse back button). The system may send a KEYCODE_BACK key press to the application when this button is pressed.

您需要从 Activity(而非视图)覆盖 onKeyUp 函数:

public boolean onKeyUp(int keyCode, KeyEvent event) 
{
    if (keyCode == KeyEvent.KEYCODE_BACK) 
    {
        //todo
    }
}

像这样在 onBackPressed() 中使用 Intent:

    @Override
    public void onBackPressed() 
    {
    Intent BackIntent = new Intent(getApplicationContext(), NewActivity.class);
    startActivityForResult(BackIntent);
    finish();
    }