How to prevent going back to the previous activity?

前端 未结 13 968
眼角桃花
眼角桃花 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:50

    Put finish() just after

    Intent i = new Intent(Summary1.this,MainActivity.class);
                startActivity(i);
    finish();
    
    0 讨论(0)
  • 2020-11-27 09:51
    @Override
    public void onBackPressed() {
    }
    

    When you create onBackPressed() just remove super.onBackPressed();and that should work

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-27 09:52

    Put

    finish();
    

    immediately after ActivityStart to stop the activity preventing any way of going back to it. Then add

    onCreate(){
        getActionBar().setDisplayHomeAsUpEnabled(false);
        ...
    }
    

    to the activity you are starting.

    0 讨论(0)
  • 2020-11-27 09:56

    paulsm4's answer is the correct one. If in onBackPressed() you just return, it will disable the back button. However, I think a better approach given your use case is to flip the activity logic, i.e. make your home activity the main one, check if the user is signed in there, if not, start the sign in activity. The reason is that if you override the back button in your main activity, most users will be confused when they press back and your app does nothing.

    0 讨论(0)
  • 2020-11-27 09:58

    My suggestion would be to finish the activity that you don't want the users to go back to. For instance, in your sign in activity, right after you call startActivity, call finish(). When the users hit the back button, they will not be able to go to the sign in activity because it has been killed off the stack.

    0 讨论(0)
提交回复
热议问题