简体   繁体   中英

How to disable previous activity in Android

Sorry for my bad English.

I have two activity. called Act1 and Act2

Act2 will be started when a Button in Act1 is clicked (startActivity). My question is how to disabled back button in Act2 so, I cannot return to Act1.

Is it possible. Thank you.

How to overcome this problem :

Override onKeyDown Method, end Set finished();

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

It's been asked before, so you'll find plenty of good answers here:

Override back button to act like home button

Just override the back key and call finish() instead. That way it won't go back to the first activity, it'll just close.

After startActivity(i); call finish() to close previous activity. or use Intent.FLAG_ACTIVITY_NO_HISTORY

There are several answers. Some you can find here: Removing an activity from the history stack

You can also override the backbutton to do exactly what you want.

Basically you need this,

Intent.FLAG_ACTIVITY_CLEAR_TASK

This clears your current activity stack, ie

if you have activity A and it starts activity B with this flag pressing the back button will not return you to Activity B because your stack now has only B.

This method is cleaner and requires less code than overriding the back button.

Since it sounds like you want to make it so the back button doesn't go back to Activity 1, but you probably still need a functional back button in Acitity 2 (maybe to deal with a potential Activity 3 or to handle the Fragment Backstack), the simplest thing is to leave the back button functionality as is, and simply wipe Activity 1 from the backstack. Do this by calling finish() on Activity 1 as you switch to Activity 2:

// This is in Activity 1. It is how we switch to Activity 2:
Intent intent = new Intent(this, Activity2.class);      
startActivity(intent);
finish();
// And now Activity 1 cannot be navigated back to with the back button
// but the back button functionality remains intact.

If you leave it like below to I presume it wont crash

@Override 

public boolean onKeyDown(int keyCode, KeyEvent event) { if ((keyCode == KeyEvent.KEYCODE_BACK)) {

} 
return super.onKeyDown(keyCode, event); 

}

use this code in activiy 2...

public boolean onKeyDown(int keyCode, KeyEvent event) {

             switch(keyCode){
             case KeyEvent.KEYCODE_BACK:

             break;
             }
             return false;
             }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM