Fragment OnBackPressed Event

Hello Everybody,
i'm kinda new in android developpement, and i got a small problem working out my App.
here is the problem : I have 4 Fragments A,B,C,D
i can work around each of them using transaction say A->B->C->D
and reversely, on pressing back button i can walk back i.e D->C->B->A-> Exit App
But i wish when i press back button, say D->C-> (Exit App on back button press when fragment C is showing )

what event should pop this ...its being driving me crazy for some days. Please HELP!! any help shall be highly appreciated.

Best Answer

  • ProgrammerCMRProgrammerCMR US ✭✭
    Accepted Answer

    hello Everybody! this worked for me finally.
    Step 1 : define a boolean Variable (Say "var") in mainActivity.cs that shall tell when youre in the desired fragment
    by default, turn it to False
    public static Boolean var = false;
    Step 2 : In the desired fragment call this variable by using MainActivity.var and change is value to true
    MainActivity.var = true;
    step 3 : call Onbackpressed override (Before the OnCreate method) in MainActivity.cs and apply the required action (for me close)
    public override void OnBackPressed()
    {
    base.OnBackPressed();
    if (var)
    {
    // We're in Fragment C.
    Finish();
    }
    }

    Thanks to those who cared!!

Answers

  • Luis_dmLuis_dm USMember ✭✭✭
     public override void OnBackPressed()
            {
    
    ///You conditions 
    
     if (drawerLayout.IsDrawerOpen(GravityCompat.Start))
                    {
                        drawerLayout.CloseDrawers();
    }
    }
    

    drawerLayou is a DrawerLayout.

  • ProgrammerCMRProgrammerCMR USMember ✭✭

    HELLO, thanks for answering !
    when i try this method, i get the following error on the OnBackPressed method : fragmentC.OnbackPressed()': no suitable method found to override

  • Luis_dmLuis_dm USMember ✭✭✭

    put some of code, please..

  • ProgrammerCMRProgrammerCMR USMember ✭✭
    Accepted Answer

    hello Everybody! this worked for me finally.
    Step 1 : define a boolean Variable (Say "var") in mainActivity.cs that shall tell when youre in the desired fragment
    by default, turn it to False
    public static Boolean var = false;
    Step 2 : In the desired fragment call this variable by using MainActivity.var and change is value to true
    MainActivity.var = true;
    step 3 : call Onbackpressed override (Before the OnCreate method) in MainActivity.cs and apply the required action (for me close)
    public override void OnBackPressed()
    {
    base.OnBackPressed();
    if (var)
    {
    // We're in Fragment C.
    Finish();
    }
    }

    Thanks to those who cared!!

Sign In or Register to comment.