How can I detect the clicking of a tab button in Xamarin.Forms?
I know you want to avoid using custom renderers, but this is only possible by using a Custom Renderer.
Code
Xamarin.Android Custom Renderer
using Android.Content;
using Android.Support.Design.Widget;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
using Xamarin.Forms.Platform.Android.AppCompat;
[assembly: ExportRenderer(typeof(MainPage), typeof(MainPageRenderer))]
namespace YourNameSpace
{
public class MainPageRenderer : TabbedPageRenderer, TabLayout.IOnTabSelectedListener
{
MainPage _page;
public MainPageRenderer(Context context) : base(context) { }
protected override void OnElementChanged(ElementChangedEventArgs<TabbedPage> e)
{
base.OnElementChanged(e);
if (e.NewElement != null)
_page = e.NewElement as MainPage;
else
_page = e.OldElement as MainPage;
}
void TabLayout.IOnTabSelectedListener.OnTabReselected(TabLayout.Tab tab)
{
System.Diagnostics.Debug.WriteLine("Tab Reselected");
//Handle Tab Reselected
}
}
}
Xamarin.iOS Custom Renderer
using System;
using System.Diagnostics;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
[assembly: ExportRenderer(typeof(MainPage), typeof(MainPageRenderer))]
namespace YourNameSpace
{
public class MainPageRenderer : TabbedRenderer
{
MainPage _page;
protected override void OnElementChanged(VisualElementChangedEventArgs e)
{
base.OnElementChanged(e);
if (e.NewElement != null)
_page = e.NewElement as MainPage;
else
_page = e.OldElement as MainPage;
try
{
if (ViewController is UITabBarController tabBarController)
tabBarController.ViewControllerSelected += OnTabbarControllerItemSelected;
}
catch (Exception exception)
{
Debug.WriteLine(exception);
}
}
void OnTabbarControllerItemSelected(object sender, UITabBarSelectionEventArgs eventArgs)
{
if (_page?.CurrentPage?.Navigation != null && _page.CurrentPage.Navigation.NavigationStack.Count > 0)
{
Debug.WriteLine("Tab Tapped");
//Handle Tab Tapped
}
}
}
}
Code credit: @Kyle https://stackoverflow.com/a/42909203/5953643