How to prevent going back to the previous activity?

前端 未结 13 1020
眼角桃花
眼角桃花 2020-11-27 09:10

When the BACK button is pressed on the phone, I want to prevent a specific activity from returning to its previous one.

Specifically, I have login and sign up screen

13条回答
  •  南方客
    南方客 (楼主)
    2020-11-27 10:12

    Since there are already many great solutions suggested, ill try to give a more dipictive explanation.

    How to skip going back to the previous activity?

    Remove the previous Activity from Backstack. Simple

    How to remove the previous Activity from Backstack?

    Call finish() method

    The Normal Flow:


    All the activities are stored in a Stack known as Backstack.
    When you start a new Activity(startActivity(...)) then the new Activity is pushed to top of the stack and when you press back button the Activity is popped from the stack.
    One key point to note is that when the back button is pressed then finish(); method is called internally. This is the default behavior of onBackPressed() method.

    So if you want to skip Activity B?

    ie A<--- C

    Just add finish(); method after your startActvity(...) in the Activity B

    Intent i = new Intent(this, C.class);
    startActivity(i);
    finish();
    

提交回复
热议问题