Forum Xamarin.Android

Fragments - OnBackPressed() or similar functionality

SoDevTCSoDevTC USUniversity ✭✭

So I'm trying to find a way of implementing OnBackPressed within a fragment but having no luck. I've tried using keylisteners but they dont seem to work, and inside the fragment I try using public override void OnBackPressed() but keeps coming up saying "No suitable method found to override". I have the OnBackPressed method implemented in my main activity, but need this for a fragment specific interaction.

Any help in trying to fix this is greatly appreciated.

Answers

  • TrevorBalcomTrevorBalcom USMember ✭✭

    This is supposed to be handled in the Activity. Here is an example solution:

    public interface IBackButtonListener
    {
        void OnBackPressed();
    }
    

    Then in your Activity:

    public override void OnBackPressed()
    {
        // Ignoring stuff about DrawerLayout, etc for demo purposes.
        var currentFragment = SupportFragmentManager.FindFragmentById(Resource.Id.content_frame);
        var listener = currentFragment as IBackButtonListener;
        if (listener != null)
        {
            listener.OnBackPressed();
            return;
        }
        base.OnBackPressed();
    }
    

    The last step is to implement the IBackButtonListener interface in any fragments where you're interested in capturing the back button press.

Sign In or Register to comment.