1

In Android 13 the OnBackPressed method has become deprecated. How can i implement this code in Xamarin.Android?

@Override
void onCreate() {
  if (BuildCompat.isAtLeastT()) {
    getOnBackInvokedDispatcher().registerOnBackInvokedCallback(
        OnBackInvokedDispatcher.PRIORITY_DEFAULT,
        () -> {
          /**
          * Code here
          */
        }
    );
  }
}

The code above is the Java example from the official android dev website, but i can't find the replacements for this in Xamarin. Can someone translate this to C#?

This is what Visual studio suggests, but it doesn't help at all.

Warning CS0672:Member 'MainActivity.OnBackPressed()' overrides obsolete member 'Activity.OnBackPressed()'. Add the Obsolete attribute to 'MainActivity.OnBackPressed()'.    

2 Answers2

1

You can try to use OnBackPressedDispatcher.AddCallback()

MainAcivity.cs

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        if (BuildCompat.IsAtLeastT)
        {
        OnBackPressedDispatcher.AddCallback(new CustomOnBackPressed(true));
        }

CustomOnBackPressed.cs

public class CustomOnBackPressed : OnBackPressedCallback
{
    public OnBack(bool enabled) : base(enabled)
    {
    }

    public override void HandleOnBackPressed()
    {
        //code that handles back button pressed
    }
}

Related question

onBackPressed() deprecated, What is the alternative?

Cfun
  • 8,442
  • 4
  • 30
  • 62
  • This code kind of works, but when i add android:enableOnBackInvokedCallback="true" to AndroidManifest.xml as adviced in [android docs](https://developer.android.com/guide/navigation/predictive-back-gesture), the custom functionality no longer happens. I haven't researched that much about the predictive back gesture so that might be the right outcome, but the custom code at least does not work. – Niilo Poutanen Oct 14 '22 at 19:09
  • i see in VS that MAUI is supporting up to API 32 for now, while what you linked has been added in android API 33. could be the reason also why i cannot find `OnBackInvokedCallback()` – Cfun Oct 14 '22 at 19:41
0

There are a series of Xamarin.Android tutorials using the NavigationComponent at https://github.com/gmck. As you progress through the projects, you will see the introduction of OnBackPressedCallback which is used extensively in the later projects.

user2153142
  • 431
  • 1
  • 4
  • 7