Search code examples
xamarin.formscustom-renderer

How to execute a platform (Android) specific method within a ButtonOnClick() using a Xamarin.Forms custom renderer.


Introduction:

I am starting with code from:

https://github.com/xamarin/xamarin-forms-samples/tree/master/CustomRenderers/Entry/Android

to study custom renderers. I am doing this because there is code that only executes on the android platform. Lets call this "androidMethod()" and belongs in the Android codebase (not the shared library). I have noticed that most of the examples I have found have utilized customRenderers for making platform specific UI modifications (like the example in the link) but I intend to make no changes to the UI, rather I am trying to place a platform specific method in a Xamarin.Forms ButtonOnClick() method as the code below indicates.

The code below is similar to the code you will find in the MyEntryRenderer.cs from the link but you will see that it was modified to apply to a button instead of an entry.

MyButtonRenderer.cs:

using Xamarin.Forms.Platform.Android;
using Xamarin.Forms;
using CustomRenderer;
using CustomRenderer.Android;
using Android.Content;

[assembly: ExportRenderer(typeof(MyButton), typeof(MyButtonRenderer))]
namespace CustomRenderer.Android
{
    class MyButtonRenderer : ButtonRenderer
    {
        private Button androidButton;

        public MyButtonRenderer(Context context) : base(context)
        {
        }

        protected override void OnElementChanged(ElementChangedEventArgs<Button> e)
        {
            base.OnElementChanged(e);

            if (Control != null)
            {
                //I want to be able to do something like this:
                ButtonOnClick(androidMethod());
            }
        }
    }
}

How do I get androidMethod(); to execute in this context. The samples I find are limited so please try to limit your response to something that would be compatible with the example. Thankyou!


Solution

  • if you want to execute a platform specific method, I would use DepenencyService instead of a Custom Renderer