Is it possible to override onBackPressed()
for only one activity ?
On back button click I want to call a dialog on a specific Activity, but in all other activities i want it to work as it worked before (going to previous activities).
EDITED
Thank you everyone for your answers, I already had everything like you told me, but my problem was that when i was clicking back button on another Activity, I was going to my previous Activity (The one where i had back button Overridden) and i thought that it wasn't working, i thought it was overriding onBackPressed()
in whole Application, now i got it.
This question is related to
android
android-intent
event-handling
overriding
Try This Its working
@Override
public void onBackPressed(){
super.onBackPressed();
Intent i=new Intent(Intent.ACTION_MAIN);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
finish();
}
Just use the following code with initializing a field
private int count = 0;
@Override
public void onBackPressed() {
count++;
if (count >=1) {
/* If count is greater than 1 ,you can either move to the next
activity or just quit. */
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
finish();
overridePendingTransition
(R.anim.push_left_in, R.anim.push_left_out);
/* Quitting */
finishAffinity();
} else {
Toast.makeText(this, "Press back again to Leave!", Toast.LENGTH_SHORT).show();
// resetting the counter in 2s
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
count = 0;
}
}, 2000);
}
super.onBackPressed();
}
Override the onBackPressed()
method as per the example by codeMagic, and remove the call to super.onBackPressed();
if you do not want the default action (finishing the current activity) to be executed.
You may just call the onBackPressed()and if you want some activity to display after the back button you have mention the
Intent intent = new Intent(ResetPinActivity.this, MenuActivity.class);
startActivity(intent);
finish();
that worked for me.
At first you must consider that if your activity which I called A extends another activity (B) and in both of
them you want to use onbackpressed function then every code you have in B runs in A too. So if you want to separate these you should separate them. It means that A should not extend B , then you can have onbackpressed separately for each of them.
Best and most generic way to control the music is to create a mother Activity in which you override startActivity(Intent intent)
- in it you put shouldPlay=true
,
and onBackPressed()
- in it you put shouldPlay = true
.
onStop
- in it you put a conditional mediaPlayer.stop with shouldPlay as condition
Then, just extend the mother activity to all other activities, and no code duplicating is needed.
Just call the onBackPressed()
method in the activity you want to show the dialog and inside it show your dialog.
Source: Stackoverflow.com