John Dwyer
John Dwyer

Reputation: 65

Override back button on xamarin android app

I am building an application using Xamarin and it's Android Player for Android. Whenever I hit the back button it seems to back out of the application completely. I want to be able to change this default to go back to the previous page in my app. How do I override the back button behavior?

Upvotes: 2

Views: 2269

Answers (3)

Jared
Jared

Reputation: 702

So the previous answer is correct, you can trap the hardware back button and do whatever you want with it. But I want to make sure you understand why this is happening. Android handles the hardware back button for you, and most of the time, letting Android handle it will work, it knows what to do.

But in your case, you're not actually navigating at all. Your click handler is removing one layout file and replacing it with another. This is the equivalent of showing/hiding a div in web development. You're not actually changing the screen(page).

Because of this, when you hit the back button, you're still on the first (and only) screen in your app, so the OS does the only thing it knows to do, it closes the app.

If you want to continue with the paradigm of showing/hiding layouts in lieu of actually navigating, I would trap the hardware back button and re-swap your layout files.

public override bool OnKeyDown(Keycode keyCode, KeyEvent e)
{
    if (keyCode == Keycode.Back) {
       SetContentView(Resource.Layout.Login)
       return false;
    }

    return true;
} 

But the true solution that I would recommend would be to read up on how to truly navigate in Xamarin Android. Swapping your layout files and putting all the logic for your entire app in one Activity will be very hard to maintain.

Upvotes: 3

SushiHangover
SushiHangover

Reputation: 74094

You can capture the OnKeyDown and decide whether to allow the Back button to ripple up the event chain or not:

public override bool OnKeyDown(Keycode keyCode, KeyEvent e)
{
    if (keyCode == Keycode.Back) {
       Toast.MakeText (this, "Back button blocked", ToastLength.Short).Show ();
       return false;
    }
    Toast.MakeText (this, "Button press allowed", ToastLength.Short).Show ();
    return true;
} 

Upvotes: 1

user1230268
user1230268

Reputation: 221

you can handle that in the OnBackPressed() event.

Upvotes: 0

Related Questions