XamarinForms – Overriding PageRenderer and NavigationService


After further implementation on my pet project, I realized that my previous solution on the page renderers would cause the NavigationService to fail from going back. So with more experimentation, I’ve discovered a way to preserve that functionality and still allow the page renderers to override the default view functionality.

using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;

[assembly: ExportRenderer(typeof(FooPage), typeof(FooPageRenderer))]
namespace FooApp.Droid.Renderer
{
    public class FooPageRenderer : PageRenderer
    {
        private Android.Views.ViewGroup parentView;
        private Android.Views.View origView;
        private Android.Views.View newView;

        protected override void OnElementChanged(ElementChangedEventArgs e)
        {
            base.OnElementChanged(e);
			
            var activity = this.Context as MainActivity;
            var newView = activity.FindViewById(Resource.Layout.foo);
            parentView = activity.Window.DecorView as ViewGroup;
            origView = parentView.GetChildAt(0);
			
            parentView.RemoveView(origView);
            parentView.AddView(newView);
        }

		private void Restore()
		{
			if (origView != null)
			{
				parentView.RemoveView(newView);
				parentView.AddView(origView);
			}
		}
    }
}

Leave a Reply