我正在创建 xamarin 表单应用程序,我想对导航后退按钮执行一些操作。有什么办法可以做到这一点吗?
附言:>软件后退按钮,而不是硬件后退按钮。
在本文中,您将找到所有内容。
如果文章在某个时候消失或更改,您将在此处找到解决方案的细节。
您需要创建自定义内容页面
namespace WhateverYourNamespace
{
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);
}
}
}
}
如你所见,我们将在 Xamarin 窗体代码级别订阅一个操作事件,并从 Xamarin 本机项目级别调用该事件。
还有一个 bool 属性用于启用或禁用"后退按钮"单击事件的重写,以便您可以决定是否将重写事件作为页面属性订阅。
安卓 : 您需要覆盖 MainActivity 类中的 OnOptionsItemSelected(( 事件,以便在 Android 中捕获 Xamarin Forms 的导航栏后退按钮单击。
public override bool OnOptionsItemSelected(IMenuItem item)
{
// check if the current item id
// is equals to the back button id
if (item.ItemId == 16908332)
{
// retrieve the current xamarin forms page instance
var currentpage = (CoolContentPage)
Xamarin.Forms.Application.
Current.MainPage.Navigation.
NavigationStack.LastOrDefault();
// check if the page has subscribed to
// the custom back button event
if (currentpage?.CustomBackButtonAction != null)
{
// invoke the Custom back button action
currentpage?.CustomBackButtonAction.Invoke();
// and disable the default back button action
return false;
}
// if its not subscribed then go ahead
// with the default back button action
return base.OnOptionsItemSelected(item);
}
else
{
// since its not the back button
//click, pass the event to the base
return base.OnOptionsItemSelected(item);
}
}
public override void OnBackPressed()
{
// this is not necessary, but in Android user
// has both Nav bar back button and
// physical back button its safe
// to cover the both events
// retrieve the current xamarin forms page instance
var currentpage = (CoolContentPage)
Xamarin.Forms.Application.
Current.MainPage.Navigation.
NavigationStack.LastOrDefault();
// check if the page has subscribed to
// the custom back button event
if (currentpage?.CustomBackButtonAction != null)
{
currentpage?.CustomBackButtonAction.Invoke();
}
else
{
base.OnBackPressed();
}
}
iOS :iOS 您需要在 CoolContentPageRenderer 类中覆盖 ViewWillAppear(( 方法。
因此,下面的代码应该放在你的CoolContentPageRenderer类中。
public override void ViewWillAppear(bool animated)
{
base.ViewWillAppear(animated);
if (((CoolContentPage)Element).EnableBackButtonOverride)
{
SetCustomBackButton();
}
}
private void SetCustomBackButton()
{
// Load the Back arrow Image
var backBtnImage =
UIImage.FromBundle("iosbackarrow.png");
backBtnImage =
backBtnImage.ImageWithRenderingMode
(UIImageRenderingMode.AlwaysTemplate);
// Create our Button and set Edge
// Insets for Title and Image
var backBtn = new UIButton(UIButtonType.Custom)
{
HorizontalAlignment =
UIControlContentHorizontalAlignment.Left,
TitleEdgeInsets =
new UIEdgeInsets(11.5f, 15f, 10f, 0f),
ImageEdgeInsets =
new UIEdgeInsets(1f, 8f, 0f, 0f)
};
// Set the styling for Title
// You could set any Text as you wish here
backBtn.SetTitle("Back", UIControlState.Normal);
// use the white color in ios back button text
backBtn.SetTitleColor(UIColor.White,
UIControlState.Normal);
backBtn.SetTitleColor(UIColor.LightGray,
UIControlState.Highlighted);
backBtn.Font = UIFont.FromName("HelveticaNeue",
(nfloat)17);
// Set the Image to the button
backBtn.SetImage(backBtnImage, UIControlState.Normal);
// Allow the button to Size itself
backBtn.SizeToFit();
// Add the Custom Click event you would like to
// execute upon the Back button click
backBtn.TouchDown += (sender, e) =>
{
// Whatever your custom back button click handling
if(((CoolContentPage)Element)?.
CustomBackButtonAction != null)
{
((CoolContentPage)Element)?.
CustomBackButtonAction.Invoke();
}
};
//Set the frame of the button
backBtn.Frame = new CGRect(
0,
0,
UIScreen.MainScreen.Bounds.Width / 4,
NavigationController.NavigationBar.Frame.Height);
// Add our button to a container
var btnContainer = new UIView(
new CGRect(0, 0,
backBtn.Frame.Width, backBtn.Frame.Height));
btnContainer.AddSubview(backBtn);
// A dummy button item to push our custom back button to
// the edge of screen (sort of a hack)
var fixedSpace =
new UIBarButtonItem(UIBarButtonSystemItem.FixedSpace)
{
Width = -16f
};
// wrap our custom back button with a UIBarButtonItem
var backButtonItem = new UIBarButtonItem("",
UIBarButtonItemStyle.Plain, null)
{
CustomView = backBtn
};
// Add it to the ViewController
NavigationController.TopViewController.
NavigationItem.LeftBarButtonItems
= new[] { fixedSpace, backButtonItem };
}
如何使用它 :
<WhateverYourNamespace:CoolContentPage
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:WhateverYourNamespace=
"clrnamespace:XFNavBarBackBtnClickOverride;
assembly=XFNavBarBackBtnClickOverride"
x:Class="XFNavBarBackBtnClickOverride.Page2"
Title="Page 3"
EnableBackButtonOverride="True"
BackgroundColor="#00bfff">
<StackLayout
Spacing="20"
Padding="20,10,20,10"
VerticalOptions="Center"
HorizontalOptions="Center" >
<Label Text="This is the cool page,
which has the Navigation Bar Back button
click overriden. How go ahead and click that Back
button! ;)"
FontSize="20"
HorizontalTextAlignment="Center"
TextColor="White"/>
</StackLayout>
</WhateverYourNamespace:CoolContentPage>
对于 ANDROID,请在 LoadApplication(new App((( 行之后的主活动 OnCreate(( 中添加此内容。
Android.Support.V7.Widget.Toolbar toolbar
= this.FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbarSetSupportActionBar(toolbar);