覆盖导航栏后退按钮点击Xamarin,表单

wbgh16ku  于 2022-12-31  发布在  其他
关注(0)|答案(1)|浏览(182)

有没有办法在点击导航栏后退图标和退出页面之前显示一条警告信息?我试过这个solution,但它不起作用。

i2byvkas

i2byvkas1#

如果你想捕捉在android平台中点击操作栏的后退按钮,你可以尝试覆盖MainActivity类中的OnOptionsItemSelected(),它允许我们捕捉导航栏的后退按钮点击。
请遵循以下步骤:
1.创建基本内容页CoolContentPage.cs

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);
        }
    }
}

2.覆盖MainActivity类中的OnOptionsItemSelected()事件,以捕获Android for Xamarin Forms中的导航栏后退按钮点击。

public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity 
{
    protected override void OnCreate(Bundle savedInstanceState)
    {
        //TabLayoutResource = Resource.Layout.Tabbar;
        ToolbarResource = Resource.Layout.Toolbar;

        base.OnCreate(savedInstanceState);

        Xamarin.Essentials.Platform.Init(this, savedInstanceState);
        global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
        LoadApplication(new App());

        AndroidX.AppCompat.Widget.Toolbar toolbar
            = this.FindViewById<AndroidX.AppCompat.Widget.Toolbar>(Resource.Id.toolbar);
        SetSupportActionBar(toolbar);
    }

    public override bool OnOptionsItemSelected(IMenuItem item)
    {
        // check if the current item id 
        // is equals to the back button id
        if (item.ItemId == 16908332) // xam forms nav bar back button id
        {
            // 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 really not necessary, but in Android user has both Nav bar back button 
        // and physical back button, so its safe to cover the both events

        var currentpage = (CoolContentPage)Xamarin.Forms.Application.Current.
            MainPage.Navigation.NavigationStack.LastOrDefault();

        if (currentpage?.CustomBackButtonAction != null)
        {
            currentpage?.CustomBackButtonAction.Invoke();
        }
        else
        {
            base.OnBackPressed();
        }
    }
    public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
    {
        Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);

        base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}

这里,我们需要在文件夹layout中创建Toolbar.xml
Toolbar.xml

<androidx.appcompat.widget.Toolbar 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    android:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

3.在Xamarin表单中,我们可以使用上面创建的CoolContentPage作为Xamarin表单解决方案中的XAML页面:

    • 主页. xaml**
<?xml version="1.0" encoding="utf-8" ?> 
<xfbackbtnapp:CoolContentPage  xmlns:xfbackbtnapp="clr-namespace:XFBackBtnApp"
                               xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="XFBackBtnApp.MainPage"
             EnableBackButtonOverride="False"
             Title="Home Page"
             BackgroundColor="#00bfff"                  
                               >

    <StackLayout
    Spacing="20"
    Padding="20,10,20,10"
    VerticalOptions="Center"
    HorizontalOptions="Center" >

        <Label Text="Welcome to Navigation Bar Back button Click overriding in Xamarin Forms!"
           FontSize="20"
           HorizontalTextAlignment="Center"
           TextColor="White"/>

        <Button Text="Open Next Page" FontSize="15" BackgroundColor="White" Clicked="OpenPageButton_OnClicked"></Button>

    </StackLayout>

</xfbackbtnapp:CoolContentPage>
    • 主页. xaml. cs**
public partial class MainPage : CoolContentPage 
{
    public MainPage()
    {
        InitializeComponent();
    }

    private void OpenPageButton_OnClicked(object sender, EventArgs e)
    {
        Navigation.PushAsync(new Page1());
    }
}
    • 第一页. xaml**
<?xml version="1.0" encoding="utf-8" ?> 
<xfbackbtnapp:CoolContentPage  xmlns:xfbackbtnapp="clr-namespace:XFBackBtnApp" 
                               xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
              EnableBackButtonOverride="False"
             BackgroundColor="#00bfff"
             Title="Page 1"
             x:Class="XFBackBtnApp.Page1">
    <ContentPage.Content>
        <StackLayout
    Spacing="20"
    Padding="20,10,20,10"
    VerticalOptions="Center"
    HorizontalOptions="Center" >

            <Label Text="Ok, this is just a normal Page! Click next Page to see the Navigation Bar Back button click overridden behavior..."
           FontSize="20"
           HorizontalTextAlignment="Center"
           TextColor="White"/>

            <Button Text="Open Next Page" FontSize="15" BackgroundColor="White" Clicked="OpenPageButton_OnClicked"></Button>

        </StackLayout>
    </ContentPage.Content>
</xfbackbtnapp:CoolContentPage>
    • 第一页. xaml.cs**
public partial class Page1 : CoolContentPage 
{
    public Page1()
    {
        InitializeComponent();
    }

    private void OpenPageButton_OnClicked(object sender, EventArgs e)
    {
        Navigation.PushAsync(new Page2());
    }
}
    • 第二页. xaml**
<?xml version="1.0" encoding="utf-8" ?> 
<xfbackbtnapp:CoolContentPage  xmlns:xfbackbtnapp="clr-namespace:XFBackBtnApp"
                               xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="XFBackBtnApp.Page2"
             EnableBackButtonOverride="True"
             BackgroundColor="#00bfff"         
             Title="Page 2"
                               
                               >
    <ContentPage.Content>
        <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>
    </ContentPage.Content>
</xfbackbtnapp:CoolContentPage>
    • 第二页. xaml.cs**
public partial class Page2 : CoolContentPage 
{
    public Page2()
    {
        InitializeComponent();

        if (EnableBackButtonOverride)
        {
            this.CustomBackButtonAction = async () =>
            {
                var result = await this.DisplayAlert(null,
                    "Hey wait now! are you sure " +
                    "you want to go back?",
                    "Yes go back", "Nope");

                if (result)
                {
                    await Navigation.PopAsync(true);
                }
            };
        }
    }
}

注:
1.这里,我在Page2.xaml的根目录下添加了属性EnableBackButtonOverride="True",那么如果我们按下页面顶部Toolbar的后退按钮或者按下手机的软后退按钮,就会弹出一个DisplayAlert
2.如果你想在iOS中实现这个功能,你可以在Xamarin窗体中选中文章Override Navigation Bar后退按钮点击。

相关问题