Override back button to act like home button

后端 未结 10 588
小鲜肉
小鲜肉 2020-11-22 08:38

On pressing the back button, I\'d like my application to go into the stopped state, rather than the destroyed state.

In the Android docs it states:

10条回答
  •  孤街浪徒
    2020-11-22 08:59

    I've tried all the above solutions, but none of them worked for me. The following code helped me, when trying to return to MainActivity in a way that onCreate gets called:

    Intent.FLAG_ACTIVITY_CLEAR_TOP is the key.

      @Override
      public void onBackPressed() {
          Intent intent = new Intent(this, MainActivity.class);
          intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
          startActivity(intent);
      }
    

提交回复
热议问题