Skip to content

Instantly share code, notes, and snippets.

@standamikes
Last active January 8, 2019 13:53
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save standamikes/4aa9a84dd6a05ac953269808b8be0a6c to your computer and use it in GitHub Desktop.
Save standamikes/4aa9a84dd6a05ac953269808b8be0a6c to your computer and use it in GitHub Desktop.
using Android.Content;
using Android.Content.Res;
using Android.Graphics.Drawables;
using System;
using System.Threading.Tasks;
using YourProject.Droid.Renderers;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
[assembly: ExportRenderer(typeof(Button), typeof(CustomButtonRenderer))]
namespace YourProject.Droid.Renderers
{
public class CustomButtonRenderer : ButtonRenderer
{
public CustomButtonRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Button> e)
{
base.OnElementChanged(e);
//get the button from XAML file
var button = Element as Button;
//create a new shape of the button with used BackgroundColor
var shape = new PaintDrawable(button.BackgroundColor.ToAndroid());
//set the CornerRadius property
//the Xamarin.Forms CornerRadius uses different unit than native Android CornerRadius,
//that's why there is *4 (you can experiment and find a better solution)
shape.SetCornerRadius(button.CornerRadius * 4);
//create a RippleDrawable out of the previous shape where is possible to add the right ripple effect
//(I used LightGray - it's possible to use whatever you want, even taking the color from the XAML button)
var ripple = new RippleDrawable(ColorStateList.ValueOf(Android.Graphics.Color.LightGray), shape, null);
//set the ripple as the native button's background
Control.SetBackground(ripple);
//this will remove the shadow behind the native button
Control.StateListAnimator = null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment