Reputation: 6912
I try the code below to call another activity while pressing the back button:
@Override
public boolean onKeyUp(int keyCode, KeyEvent msg) {
switch(keyCode) {
case(KeyEvent.KEYCODE_BACK):
Intent intent = new Intent(AActivity.this, BActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Window w = NASGroup.group.getLocalActivityManager().startActivity("BActivity", intent);
View view = w.getDecorView();
MyGroup.group.setContentView(view);
return true;
}
return false;
}
But when I press the back button, it get out of the app.
I see the logcat, it does not run the function onKeyUp
and doesn't output any message.
The same code in onKeyUp
, I try to below code to a button in layout and it works.
cancel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(AActivity.this, BActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Window w = NASGroup.group.getLocalActivityManager().startActivity("BActivity", intent);
View view = w.getDecorView();
MyGroup.group.setContentView(view);
}
});
How can I modify it?
Upvotes: 4
Views: 14982
Reputation: 1305
Try like this...
@Override
public void onBackPressed() {
Intent BackpressedIntent = new Intent();
BackpressedIntent .setClass(getApplicationContext(),TargetActivity.class);
BackpressedIntent .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(BackpressedIntent );
finish();
}
Upvotes: 2
Reputation: 4908
If you are within Activity you can use onBackPressed which is a built-in method to handle back key press.
Upvotes: 1
Reputation: 6856
To handle back press you have to override Onbackpress method.
@Override
public void onBackPressed() {
finish();
Intent intent = new Intent(Myactivity.this, other.class);
startActivity(intent);
}
Upvotes: 18
Reputation: 2494
For back button you have to override the OnBackPressed() in your activity as
@Override
public void onBackPressed() {
Intent intent=new Intent(currentclass.this,nextActivity.class);
startActivity(intent);
finish();
}
if you didnt finish the previous activity then no need to use intent and startActivity just call finish(); in the onBackPressed it will finish the current activity and previous activity will started.
Upvotes: 1
Reputation: 1339
Try overriding the activity's onBackPressed() method
from the docs : onBackPressed
Upvotes: 2