【问题标题】:Xamarin forms navigation back buttonXamarin 表单导航返回按钮
【发布时间】:2018-09-23 10:26:52
【问题描述】:

我是 xamarin 表单应用程序开发的新手,目前,我在覆盖工具栏后退按钮 onclick 时遇到问题。在 ios 中,我能够实现,但在 android 中它不起作用,任何人都可以帮助我了解如何在我的项目中实现这一目标。

【问题讨论】:

  • 您介意在 github 上发布您的项目吗?
  • 这个项目是一个企业,我没有权限在任何地方上传这个项目。你能帮我解决这个问题吗,如何覆盖工具栏的后退按钮点击。
  • 可能this会给你一些帮助,没有相关代码很难回答。
  • 嗨,你试过链接中的Toolbar.NavigationClick += Toolbar_NavigationClick; 吗?
  • 在我的主要活动中,我无法获取 Toolbar.NavigationClick 其显示错误。您能告诉我在构建 xamarin 表单应用程序时应该在哪里使用此方法吗

标签: android xamarin navigation toolbar back-button


【解决方案1】:

默认情况下,它仅适用于 iOS 和 Android 物理后退按钮。如果还想支持导航栏按钮,则需要使用自定义平台逻辑。看看这篇博文:Let’s Override Navigation Bar back button click in Xamarin For。他为后退按钮创建了一个带有自定义操作的通用内容页面:

 public class CoolContentPage : ContentPage
    {
        /// <summary>
        /// Gets or Sets the Back button click overriden custom action
        /// </summary>
        public Action CustomBackButtonAction { get; set; }

        public static readonly BindableProperty EnableBackButtonOverrideProperty =
               BindableProperty.Create(
               nameof(EnableBackButtonOverride),
               typeof(bool),
               typeof(CoolContentPage),
               false);

        /// <summary>
        /// Gets or Sets Custom Back button overriding state
        /// </summary>
        public bool EnableBackButtonOverride
        {
            get
            {
                return (bool)GetValue(EnableBackButtonOverrideProperty);
            }
            set
            {
                SetValue(EnableBackButtonOverrideProperty, value);
            }
        }
    }

然后他在 Anroid 代码中的 OnOptionsItemSelected 方法中调用 CustomBackAction

【讨论】:

  • 我之前在 android 主要活动支持工具栏上已经通过这篇文章无法正常工作。它越来越崩溃
【解决方案2】:

拦截返回导航(一般为导航)的最佳方法是添加 NavigationPageRenderer,以便您可以控制事件并取消或重定向它们,请查看我的回答 How to intercept Navigation Bar Back Button Clicked in Xamarin Forms?

【讨论】:

    【解决方案3】:

    我带着关于 Xamarin 表单导航返回按钮的相同问题来到这篇文章,后来发现因为 Xamarin.Forms Shell 这很容易通过覆盖 AppShell.xaml.cs 文件中的 OnNavigating 方法来完成,就像我在这里所做的那样:

    protected override void OnNavigating(ShellNavigatingEventArgs e)
    {
        if(
            // Detect Back Navigation
            e.Source == ShellNavigationSource.Pop &&
    
            // Make sure it's safe to examine the current page
            (Shell.Current != null) && 
            (Shell.Current.CurrentPage != null) &&
    
            // Cancel or not, (for example) based on what the Title of the current page is.
            (Shell.Current.Title != "My Main Page"))
        {
            e.Cancel();
            Shell.Current.GoToAsync("..");
        }
        base.OnNavigating(e);
    }
    

    以防其他人偶然发现,我在 GitHub 上放了一个示例,说明适用于 Android 和 iOS 的方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多