Search code examples
androidxamarinandroid-relativelayout

Xamarin Forms - Android button using relative layour from Resources/Layout


Visual Studio 2017 So I have an app, IOS & Android which uses Xamarin Forms. I have downloaded as RelativeLayout file into resources/Layouts.

IS there a way I can use this layout in a Custom button renderer?

All our forms are in the Xamarin project so I can't just include it in a fragment.

Am I flogginga dead horse by trying to fudge using it in a customer renderer?


Solution

  • Create a view renderer for your custom button. Then replace it with your native layout:

    [assembly: ExportRenderer(typeof(CustomButton), typeof(CustomButtonRenderer))]
    namespace App.Droid
    {
        public class CustomButtonRenderer : ViewRenderer<CustomButton, Android.Views.View>
        {
            Context _context;
            public CustomButtonRenderer(Context context) : base(context)
            {
                _context = context;
            }
    
            protected override void OnElementChanged(ElementChangedEventArgs<CustomButton> e)
            {
                base.OnElementChanged(e);
    
                if (Control == null)
                {
                    SetNativeControl(getView());
                }
            }
    
            Android.Views.View getView()
            {
                return LayoutInflater.From(_context).Inflate(Resource.Layout.custom_layout, null);
            }
        }
    }
    

    At last you can consume the custom control in XAML like:

    <StackLayout>
        <local:CustomButton />
    </StackLayout>