简体   繁体   English

防止用户返回上一个活动

[英]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". 我正在研究Xamarin.Forms项目,并且在我的PCL中创建了名为“ Login.xaml”的启动页面。 On this page a user has to fill in their credentials and sends it to an WebAPI. 用户必须在此页面上填写其凭据并将其发送到WebAPI。 When the API returns "1"/true it opens a new page called "Home.xaml". 当API返回“ 1” / true时,它将打开一个名为“ 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. 即:用户登录到第一页,webapi对其进行验证并返回“ 1”,以便打开新页面(“主页”),但是当用户按下“返回”按钮时,它将返回登录屏幕。 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 : 当您推送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 . 为此,您的登录页面必须是NavigationPage For this, you'll have to wrap it with the NavigationPage ctor: 为此,您必须将其与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 我建议您看一下文档: Xamarin表单简介-导航

As for me, calling RemovePage() was giving me all sorts of problems. 对于我来说,调用RemovePage()会给我带来各种各样的问题。

What I had to do is shift my thinking. 我要做的就是改变我的想法。 If you do Pop instead of Push , you're actually removing the page for good. 如果执行Pop而不是Push ,则实际上是永久删除该页面。 So what do you need to do in order to be able to do Pop instead of Push? 那么,您需要做些什么才能能够执行Pop而不是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: 注意:为此,您还需要将初始根页面包装在NavigationPage中,就像@germi在回答的最后一部分中说的那样:

// 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. PS:FWIW, 这是我在F#开源项目中的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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