Circular Button Using Xamarin (Custom Renderer)

The shift to appcompat has affected Android developers, while developing cross platform xamarin application. The first difference you would notice is the buttons are no longer having rounded corner despite assigning the radius. That is a define roadblock when you consider you need a perfect circular button.

However things aren’t actually that bad as it sounds to be. You cannot discount the power custom renderering brings in. What we need to do is write a custom Renderer and ensure shape is set to Oval. Let’s get hands dirty and do some coding.

class CircularButtonRender : Xamarin.Forms.Platform.Android.ButtonRenderer
{
private GradientDrawable _NormalState, _PressedState;

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

if (Control != null)
{
var button = e.NewElement;

// Create a drawable for the button's normal state
_NormalState = new Android.Graphics.Drawables.GradientDrawable();
_NormalState.SetColor(button.BackgroundColor.ToAndroid());
_NormalState.SetStroke((int)button.BorderRadius, button.BorderColor.ToAndroid());
_NormalState.SetShape(ShapeType.Oval);

_PressedState = new Android.Graphics.Drawables.GradientDrawable();
_PressedState.SetColor(button.BackgroundColor.ToAndroid());
_PressedState.SetStroke((int)button.BorderRadius, button.BorderColor.ToAndroid());
_PressedState.SetShape(ShapeType.Oval);

// Add the drawables to a state list and assign the state list to the button
var sld = new StateListDrawable();
sld.AddState(new int[] { Android.Resource.Attribute.StatePressed }, _PressedState);
sld.AddState(new int[] { }, _NormalState);
Control.SetBackground(sld);
}
}

}

 The entire source can be found in my Git project here [GitHub].