Android Overriding onBackPressed()
Asked Answered
P

10

69

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.

Phonograph answered 20/8, 2013 at 14:23 Comment(1)
refer hereEmogene
F
156

Yes. Only override it in that one Activity with

@Override
public void onBackPressed()
{
     // code here to show dialog
     super.onBackPressed();  // optional depending on your needs
}

don't put this code in any other Activity

Fifine answered 20/8, 2013 at 14:25 Comment(10)
How above code work in fragment? Is this any solutionsJoscelin
hello i have a same problem my activity 2 is going on activity 1 but i do not want to go activity 1 if i clicked back on activity 2 my application should exit. how can i do that ?Prankster
@Tabishkhan just call finish() on activity 1 after starting the intent for activity 2. Then, activity 2 will be the only one in the stackFifine
@Fifine how we can reduce duplication of this method? mean I want the same functionality for 5 activities when they click back. So how I can use the same functionality in all activities?Hamachi
@UnKnown create an activity to extend in your others and put the code in that super activityFifine
@Fifine how I will access the field of child class in the super activity? which I will use in the onBackPressed()Hamachi
@UnKnown if it does the same thing for all then, ideally, it will contain everything it needs to complete. You may be better off creating a question with the relevant code and what isn't working as expected. There may be a better way but this was my first thought.Fifine
@Fifine here I have asked. #49907188Hamachi
@Fifine super.onBackPressed(); not an option because without this the activity does not return to a previous screen.Gallinacean
Leave it empty if you want to prevent going back to previous activity.Tum
L
44

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.

Loar answered 20/8, 2013 at 14:35 Comment(0)
G
6

OnBackPressed Deprecated.

Kotlin solution here:

onBackPressedDispatcher.addCallback(object: OnBackPressedCallback(true) {
            /* override back pressing */
            override fun handleOnBackPressed() {
                //Your code here
            }
        })
Guerrilla answered 28/9, 2022 at 1:50 Comment(3)
This answer provides the new approach introduced with Android 13 (SDK 33). You may find more details here stackoverflow - onBackPressed() deprecated, What is the alternative? and a migration guide at Medium - How To Migrate The Deprecated OnBackPressed Function.Garthgartner
@Aaron, thank you for your effort investing time by publishing a tutorial in 'Medium'. But I am not registered there and thus cannot access your content ('id wall'). I was wondering if you have this knowledge (how to migrate) published somewhere else. Thank you again.Matherly
Can't access it either. I googled it for you 🙄 proandroiddev.com/…Garthgartner
C
5

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.

Cabaret answered 18/5, 2015 at 10:31 Comment(0)
A
2

Just call the onBackPressed() method in the activity you want to show the dialog and inside it show your dialog.

Ambulant answered 20/8, 2013 at 14:25 Comment(0)
P
2

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();
}
Parenteral answered 21/2, 2018 at 6:17 Comment(0)
M
0

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.

Marquisette answered 23/4, 2015 at 22:57 Comment(0)
C
0

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.

Coaxial answered 29/2, 2016 at 11:52 Comment(0)
P
0

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();
}
Prankster answered 30/8, 2017 at 6:25 Comment(0)
S
0

A simple Kotlin solution, Create an extension function below

fun Fragment.onBackPressed(
    navigateToHomeGraph: () -> Unit
) {
    val onBackPressedDispatcher = requireActivity().onBackPressedDispatcher
    onBackPressedDispatcher.addCallback(
        viewLifecycleOwner,
        object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                navigateToHomeGraph()
            }
        }
     )
}

Now you can simply call this on your Fragment and pass your desired destination.

onBackPressed {
    findNavController().navigate(R.id.destination_nav_graph)
}
Steady answered 7/9, 2023 at 5:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.