[FIXED] Using OnBackPressedCallback in Xamarin

Issue

I’m trying to implement something similar to OnBackPressed() in a fragment in Xamarin, but the only solutions I found so far are for Java.

Here is one example in Java that does what I want:

OnBackPressedCallback callback = new OnBackPressedCallback(true) {
        @Override
        public void handleOnBackPressed() {
            Toast.makeText(mContext, "back pressed", Toast.LENGTH_SHORT).show();
            
            // And when you want to go back based on your condition
            if (yourCondition) {
                this.setEnabled(false);
                requireActivity().onBackPressed();
            }
        }
    };

How could I go about converting that piece of code into C#?

Solution

UPDATE

Create an interface for handling your event:

public interface IOnBackPressedHandler
{
    bool OnBackPressed();
}

In your activity(below is just an example) setup your interface callback as follows

public class FragActivity : AppCompatActivity
{

    public override void OnBackPressed()
    {
        Fragment fragment = SupportFragmentManager.FindFragmentById(Resource.Id.yourFragmentId);
        if (!(fragment is IOnBackPressedHandler) || !((IOnBackPressedHandler)fragment).OnBackPressed()) {
            base.OnBackPressed();
        }
    }

}

Finally, your fragment would look something like that :

public class SomeFragment : Fragment, IOnBackPressedHandler
{
    public bool OnBackPressed()
    {
        //Callbacks will be received here.
        return true;
    }
}

Hope this makes it easier to understand. You can also make this method a part of your base Fragment mark it as virtual and then have all classes inherit this to keep overriding it…

OG answer:

Well you cannot have anonymous classes in C#, So just create a Class that inherits this Abstract class and you’re good:

public class HandleOnBackPressedCallback : OnBackPressedCallback
{
    public HandleOnBackPressedCallback(bool enabled) : base(enabled)
    {
    }

    public override void HandleOnBackPressed()
    {
        Toast.MakeText(context, "back pressed", ToastLength.Long).Show();

        // And when you want to go back based on your condition
        if (yourCondition)
        {
            this.setEnabled(false);
            requireActivity().onBackPressed();
        }
    }
}

Good luck!!

Answered By – FreakyAli

Answer Checked By – Terry (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published