简体   繁体   中英

Prevent user from returning to last activity

I am working on a Xamarin.Forms project, and in my PCL i created startup page called "Login.xaml". On this page a user has to fill in their credentials and sends it to an WebAPI. When the API returns "1"/true it opens a new page called "Home.xaml".

How can i prevent the user from returning to the login page when pressing on the back button on the phone? ie: The user logs in on the first page, webapi validates it and returns a "1" so the new page ("Home") gets opened, but when the user presses the Back button it returns to the login screen. This should not be possible until the app gets closed down.

You can remove the login page from the navigation stack when you're pushing your Home.xaml :

await Navigation.PushAsync(new Home());  // or whatever your page is called
Navigation.RemovePage(this);

This way there's nothing to go back to after your user gets to the homepage.

For this to work, your login page needs to be a NavigationPage . For this, you'll have to wrap it with the NavigationPage ctor:

// this goes into your App.cs where you enter your app:
public App()
{
    MainPage = new NavigationPage(new Login()); // or whatever your login page is called
}

I suggest you have a look at the documentation: Introduction to Xamarin Forms - Navigation

As for me, calling RemovePage() was giving me all sorts of problems.

What I had to do is shift my thinking. If you do Pop instead of Push , you're actually removing the page for good. So what do you need to do in order to be able to do Pop instead of Push? Insert the next page before the current page first, and then Pop:

var newRootPage = new NewRootPage();
this.Navigation.InsertPageBefore(newRootPage, this);
await this.Navigation.PopAsync();

Note: for this to work you will also need to do wrap your initial root page in a NavigationPage like @germi says in the last part of his answer:

// this goes into your App.cs where you enter your app:
public App()
{
    // or whatever your login page is called
    MainPage = new NavigationPage(new Login()); 
}

PS: FWIW this was my fix in my F# open source project.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM