How to switch from an activity to another designated one when the device back button is pressed?

StackOverflow https://stackoverflow.com/questions/23650557

  •  22-07-2023
  •  | 
  •  

Question

I am developing an app that is currently consists of 4 activities. What I want is, while I am for an example, accessing activity number 3, when I press the back button of the device, I want to be directed to activity number 1 and not to the immediate preceding activity. Any suggestions to achieve this?

Was it helpful?

Solution

override it in that one Activity with

@Override
public void onBackPressed()
{
     // code here to show your new activity
     Intent i=new Intent(MainActivity.this,MynextActivity.class);
     startActivity(i);
     super.onBackPressed();  // optional depending on your needs
}

don't put this code in any other Activity

OTHER TIPS

You can intercept android back button event by overriding onBackPressed() method and do whatever you need (For example start Activity1)

Use below code:-

@Override
public void onBackPressed()
{
    startActivity(new Intent(ThisActivity.this, WhereYouGoActivity.class));
    finish();

}

Use this code in activity B

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) 
{
    if(keyCode==KeyEvent.KEYCODE_BACK)
    {
       //use intent to call activity A

    }
    return super.onKeyDown(keyCode, event);

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top