0
votes

I'm new in Xamarin, Xamarin.Forms and C# platform.

I'm making some experiments with these technologies and now I'm searching about how to use platform specific UI components in Xamarin.Forms with a PCL project for code sharing.

Searching in the web I found some implementations of FAB button (example), but these implementations are deprecated or abandoned.

I know that is possible to Embed Native Controls into Xamarin.Forms, but this approach uses a SAP project...

My question is: Is there a way to use a FAB button (or some other platform specific UI control) into a Xamarin.Forms solution with a PCL project for code sharing? If yes, what will be the behavior in other platforms? I hope that FAB button does not appear on the iOS UI.

Thanks for the help.

1

1 Answers

1
votes

I won't suggest any third-party library here, but usually we can use Custom Renderers to use the native controls of the target platform from PCL.

For FloatingActionButton of Android platform, you can try to implement a view renderer.

For example in PCL create a class named MyFloatButton:

public class MyFloatButton : View
{
}

Then in android project create another class named MyFloatButtonRenderer for example like this:

[assembly: ExportRenderer(typeof(MyFloatButton), typeof(MyFloatButtonRenderer))]

namespace NameSpace.Droid
{
    public class MyFloatButtonRenderer : Xamarin.Forms.Platform.Android.ViewRenderer<MyFloatButton, FloatingActionButton>
    {
        private FloatingActionButton fab;

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

            if (Control == null)
            {
                fab = new FloatingActionButton(Xamarin.Forms.Forms.Context);
                fab.LayoutParameters = new LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent);
                fab.Clickable = true;
                fab.SetImageDrawable(Resources.GetDrawable(Resource.Drawable.icon));
                SetNativeControl(fab);
            }

            if (e.NewElement != null)
            {
                fab.Click += Fab_Click;
            }

            if (e.OldElement != null)
            {
                fab.Click -= Fab_Click;
            }
        }

        private void Fab_Click(object sender, EventArgs e)
        {
        }
    }
}

I hope that FAB button does not appear on the iOS UI.

If you only want this control to be shown for Android platform, you can code for example in your page's xaml of PCL for example like this:

<OnPlatform x:TypeArguments="View">
    <OnPlatform.Android>
        <local:MyFloatButton WidthRequest="50" HeightRequest="50" HorizontalOptions="Center" />
    </OnPlatform.Android>
    <OnPlatform.iOS>
        <!--use other view here-->
    </OnPlatform.iOS>
</OnPlatform>

Or you may check add this control in code behind, check this blog: Embedding Native Controls into Xamarin.Forms