Implémenter le Click de retour android – pour MasterDetails Page Xamarin Forms
Pour implémenter le click de retour d’android, pour une app utilisant MasterDetails Page il suffit de procéder en deux étape
1-Dans le projet android, Créer un renderer en utilisant le code suivant :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Support.V4.Widget;
using Android.Support.V7.Widget;
using Android.Views;
using Egee20.Droid;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
using Xamarin.Forms.Platform.Android.AppCompat;
[assembly: ExportRenderer(typeof(NavigationPage), typeof(CustomNavigationRenderer))]
namespace BackButtonCIick.Droid
{
public class CustomNavigationRenderer : NavigationPageRenderer
{
public CustomNavigationRenderer(Context context) : base(context)
{
}
protected override void OnAttachedToWindow()
{
base.OnAttachedToWindow();
Element page = Element.Parent;
MasterDetailPage masterDetailPage = null;
while (page != null)
{
if (page is MasterDetailPage)
{
masterDetailPage = page as MasterDetailPage;
break;
}
page = page.Parent;
}
if (masterDetailPage == null)
{
return;
}
var renderer = Platform.GetRenderer(masterDetailPage) as MasterDetailPageRenderer;
if (renderer == null)
{
return;
}
var drawerLayout = (DrawerLayout)renderer;
Toolbar toolbar = null;
for (int i = 0; i < ChildCount; i++)
{
var child = GetChildAt(i);
toolbar = (Toolbar)child;
if (toolbar != null)
{
break;
}
}
toolbar?.SetNavigationOnClickListener(new MenuClickListener(Element, drawerLayout));
}
private class MenuClickListener : Java.Lang.Object, IOnClickListener
{
readonly NavigationPage navigationPage;
private DrawerLayout layout;
public MenuClickListener(NavigationPage navigationPage, DrawerLayout layout)
{
this.navigationPage = navigationPage;
this.layout = layout;
}
public void OnClick(Android.Views.View v)
{
var page = navigationPage.CurrentPage as BasePage;
if (navigationPage.Navigation.NavigationStack.Count <= 1)
{
layout.OpenDrawer((int)GravityFlags.Left);
}
if (page != null)
{
if (page.OnNavigationBackButtonPressed())
{
navigationPage?.PopAsync();
}
}
else
{
navigationPage?.PopAsync();
}
}
}
}
}
2-Dans le projet partagé, créer une page BasePage et modifier le code de BasePage.xaml.cs comme suit :
using System;
using System.Collections.Generic;
using System.Text;
using Xamarin.Forms;
namespace BackButtonCIick10
{
public class BasePage : ContentPage
{
public bool OnNavigationBackButtonPressed() {
DisplayAlert(“ok”, “ok”, “ok”);
return true;
}
}
}
Réponse inspiré de AlexeiMalashkevich : https://forums.xamarin.com/discussion/87795/onoptionsitemselected-not-invoked-using-masterdetails-page-on-android
“Implémenter le Click de retour android – pour MasterDetails Page Xamarin Forms”
Advantages of this frame ?
C’est pour le développement d’applications mobile avec Xamarin Forms.