c# - 将后退按钮导航到另一个 Activity Xamarin C#

标签 c# android visual-studio xamarin

所以我试图让后退按钮从一个 Activity 导航到另一个 Activity (假设我希望 Activity1、Activity2、Activity3 导航到 mainActivity(级别选择)),因为目前它仅导航回自身然后关闭像这样的应用程序 enter image description here

我尝试将“NoHistory =true”添加到
[Activity(Label = "firstQ", NoHistory =true)]
但这根本没有做任何事情,知道什么可以解决这个问题吗?

最佳答案

NoHistory=true 属性标志实际上用于操作栏上的“向上”按钮。请参阅此处 more信息。

您想要做的是覆盖后退按钮的行为。你可以在这里做的是这样的

Activity 1:

public override void OnBackPressed()
{
    var intent = new Intent(this, typeof(MainActivity));
    StartActivity(intent);

    //base.OnBackPressed(); -> DO NOT CALL THIS LINE OR WILL NAVIGATE BACK
}

一旦在前台 Activity 上按下后退按钮,就会触发此方法。通过注释掉(或不调用)base.OnBackPressed(); 将阻止 Activity 返回,您可以启动新 Activity,即 MainActivity

现在,如果您的层次结构实际上与您所说的不同,其中 MainActivity 本质上是您的 root Activity,并且您按后退按钮返回按顺序启动其他 Activity对于主要 Activity ,您可以采取类似的方法,但需要一些额外的标志。对于本例,您可能对 FLAG_ACTIVITY_CLEAR_TOP 感兴趣。或 Xamarin 术语 ActivityFlags.ClearTop

If set, and the activity being launched is already running in the current task, then instead of launching a new instance of that activity, all of the other activities on top of it will be closed and this Intent will be delivered to the (now on top) old activity as a new Intent.

For example, consider a task consisting of the activities: A, B, C, D. If D calls startActivity() with an Intent that resolves to the component of activity B, then C and D will be finished and B receive the given Intent, resulting in the stack now being: A, B.

现在的实现几乎与添加的 Intent 标志相同。

public override void OnBackPressed()
{
    var intent = new Intent(this, typeof(MainActivity));
    intent.AddFlags(ActivityFlags.ClearTop);
    StartActivity(intent);
    //base.OnBackPressed(); -> DO NOT CALL THIS LINE OR WILL NAVIGATE BACK
}

关于c# - 将后退按钮导航到另一个 Activity Xamarin C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35926939/

相关文章:

c# - 使用 C# 以编程方式设置 sql server 用户映射

android - 在 Event.COMPLETE 不起作用后调整 Flash 加载器的大小

android - 如何创建永远不会在任务管理器中强制停止的服务/广播接收器

visual-studio - 可以使用 ReSharper 将 'foreach' 转换为 'for' 循环,反之亦然?

c# - 托管 .NET 等同于 WinBase 的 CreateFile 和 WriteFile (kernel32.dll)

c# - EF Core 6.0 无效操作异常 : The object has been removed from the model

visual-studio - 如何在 Visual Studio 2015 中使用 VSProlog?

c++ - VS2008 速成版和资源

c# - 存储过程无法正常工作错误转换数据类型

带有 BroadcastReceiver 内部类的 Android AlarmManager