How to prevent going back to the previous activity?

前端 未结 13 1047
眼角桃花
眼角桃花 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 09:52

    There are two solutions for your case, activity A starts activity B, but you do not want to back to activity A in activity B.

    1. Removed previous activity A from back stack.

        Intent intent = new Intent(activityA.this, activityB.class);
        startActivity(intent);
        finish(); // Destroy activity A and not exist in Back stack
    

    2. Disabled go back button action in activity B.

    There are two ways to prevent go back event as below,

    1) Recommend approach

    @Override
    public void onBackPressed() {
    }
    

    2)Override onKeyDown method

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode==KeyEvent.KEYCODE_BACK) {
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }
    

    Hope that it is useful, but still depends on your situations.

提交回复
热议问题