4
votes

In my Xamarin forms application I want to show a confirmation message when user clicks the back button from Main-page. Is there any way to achieve this? I overrided the OnBackButtonPressed method in my MainPage. But still the app is closing while back key press. Here is my code

protected override bool OnBackButtonPressed ()
    {
        //return base.OnBackButtonPressed ();
        return false;
    }
1

1 Answers

3
votes

You can override OnBackButtonPressed for any Xamarin.Form Page. But it only will work for the physical button in Android and Windows Phone devices.

    protected override bool OnBackButtonPressed () {
        DisplayAlert("title","message","ok");
        return true;
    }

For the virtual one, you will need to create CustomRenderers and to intercept the click handler. In iOS it can be tricky because the user can go back doing other actions (e.g. the swipe gesture). Once you intercept it you just need to create your Confirmation Message (which I assume that you know how to do it).

For iOS you can do something like this:

[assembly: ExportRenderer (typeof (YourPage), typeof (YourPageRenderer))]
namespace YourNamespace {
public class YourPageRenderer : PageRenderer {

    public override void ViewWillAppear (bool animated) {
        base.ViewWillAppear (animated);
        Action goBack = () => page.DisplayAlert("title","message","ok");

        var backButton = new NavBackButton (goBack);
        navigationItem.LeftBarButtonItem = new UIBarButtonItem (backButton);
    }
}

  public class NavBackButton : UIView {
    public NavBackButton (Action onButtonPressed) {
        SetButton (onButtonPressed);
    }

    UILabel text;
    UIImageView arrow;

    void SetButton(Action onButtonPressed){
        arrow = new UIImageView(new CGRect(-25,0, 50, 50)) { 
            Image = new UIImage("Images/back").ImageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
        };
        arrow.TintColor = Colors.DarkGreen.ToUIColor ();

        text = new UILabel(new CGRect(arrow.Frame.Width + arrow.Frame.X -15, arrow.Frame.Height /2 - 10, 40, 20))  { Text = "Back" };
        text.TextColor = Colors.DarkGreen.ToUIColor ();
        Frame = new CGRect(0,0,text.Frame.Size.Width + arrow.Frame.Width, arrow.Frame.Height);
        AddSubviews (new UIView[] { arrow, text });

        var tapGesture = new UITapGestureRecognizer (onButtonPressed);
        AddGestureRecognizer (tapGesture);

    }
    public override void TouchesBegan (Foundation.NSSet touches, UIEvent evt) {
        base.TouchesBegan (touches, evt);
        text.TextColor =  UIColor.YourColor;
        arrow.TintColor =  UIColor.YourColor;
    }

    public override void TouchesEnded (Foundation.NSSet touches, UIEvent evt){
        base.TouchesEnded (touches, evt);
        arrow.TintColor = UIColor.YourColor;
        text.TextColor = UIColor.YourColor;
    }

}
}

PS You will need to provide an arrow image ("Images/back")